VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-add-text-formatting-to-a-textarea-using-javascript/

⇱ How to Add Text Formatting to a Textarea using JavaScript? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Add Text Formatting to a Textarea using JavaScript?

Last Updated : 14 Nov, 2024

To add text formatting (such as bold, italic, or inserting special characters) to a <textarea> using JavaScript, you can manipulate the selected text or insert formatted text at the cursor position. This can be done by directly modifying the value of the <textarea> based on user interactions.

Example: Basic Text Formatting (Bold, Italic) in a Textarea

Here's how you can implement basic text formatting functions:

HTML Structure

Output:

👁 Screenshot-2024-11-14-130121
Output
👁 Screenshot-2024-11-14-130149
Bold Text
👁 Screenshot-2024-11-14-130201
Italic Text
👁 Screenshot-2024-11-14-130211
Inserting Link

Explanation

  1. wrapText(startTag, endTag) Function:
    • This function wraps the selected text in the <textarea> with specified startTag and endTag.
    • For example, clicking the "Bold" button wraps the selected text with ** (Markdown-style bold formatting).
    • It preserves the cursor position after the text is modified.
  2. insertText(textToInsert) Function:
    • This function inserts text at the cursor position in the <textarea>.
    • Useful for inserting links, special characters, or custom templates.

Example Usage

  • Bold: Select text in the <textarea> and click the "Bold" button to wrap the text with ** (e.g., **selected text**).
  • Italic: Select text in the <textarea> and click the "Italic" button to wrap the text with * (e.g., *selected text*).
  • Insert Link: Click the "Insert Link" button to insert a Markdown-style link at the cursor position.

Customizing Formatting Options

You can extend the example by adding more buttons or functions for other formatting options, such as:

  • Underline: Wrap text with <u> and </u> tags (or equivalent formatting).
  • Strikethrough: Use ~~ for Markdown or <s> tags for HTML.

This approach gives you full control over text manipulation within a <textarea> element using JavaScript

Comment
Article Tags: