lobianco
lobianco

Reputation: 6276

JavaScript - Change color of text based on regular expression

I'd like to be able to search the contents of a textarea (which will contain HTML markup that is visible to the user) with a specific regular expression that searches for specific attributes of all the HTML tags. Then I want to change the font color (within that same textarea) of the results of the search. Assume I have a submit button that will call a JS function that:

  1. Creates a variable with the value of the textarea
  2. Creates a variable with my regex search object
  3. Searches the textarea.value with the regex string and changes the font color of all matches

Is this possible?

Upvotes: 2

Views: 1876

Answers (1)

kevin628
kevin628

Reputation: 3526

Yes. But it will take some work. More than likely, you'll need to swap out your textarea with a div and set its contenteditable attribute to true. Then you can wrap matched words with a span and set the font-color for those spans.

Rich text editing from MDN

Upvotes: 2

Related Questions