Categories
JavaScript Answers

How to change color of specific words in text area with JavaScript?

Spread the love

Sometimes, we want to change color of specific words in text area with JavaScript.

In this article, we’ll look at how to change color of specific words in text area with JavaScript.

How to change color of specific words in text area with JavaScript?

To change color of specific words in text area with JavaScript, we can use a contenteditable div as the text area.

Then we can replace the matched substrings to the HTML code we want and assign it to the innerHTML property of the contentedtable div.

For instance, we write:

<div contenteditable="true" style='height: 200px'></div>

to add a contenteditable div.

Then we write:

const div = document.querySelector('div')
div.onblur = (e) => {
  e.target.innerHTML = e.target.innerHTML.replace(/select/g, (match) => {
    return `<span style='color: orange'>${match}</span>`
  })
}

to select the div with querySelector.

Then we set the div.onblur method to a function that calls e.target.innerHTML.replace to select all the substrings with the word 'select'.

Then we pass in a callback that does the replacement on all of them by replacing them with a span that sets their color to orange.

Now when we focus away from the div, we should see the color of ‘select’ change to orange.

Conclusion

To change color of specific words in text area with JavaScript, we can use a contenteditable div as the text area.

Then we can replace the matched substrings to the HTML code we want and assign it to the innerHTML property of the contentedtable div.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *