highlight text in js

How to Highlight Text Using JavaScript

Often web developers need to highlight text on their websites or applications to make it easier for readers to spot key parts of the text. You can easily do this using JavaScript. In this article, we will learn how to highlight text using JavaScript.

How to Highlight Text Using JavaScript

Let us say you have the following div that contains text, part of which needs to be highlighted.

<div id="my_div">
  Hello World. Good Morning.
</div>

Let us say you have a button that highlights text ‘World’ above, when clicked.

<button onclick="highlight('World')">Highlight</button>

When the above button is clicked, we will call the function highlight() which adds a span with class highlight around the word ‘World’ in the text above. When this happens, the CSS for element with class=highlight will be applied to the substring. For this, we will first define CSS for class highlight as shown below.

.highlight {
  background-color: yellow;
}

Next, we define function highlight() as shown below.

function highlight(text) {
  var inputText = document.getElementById("my_div");
  var innerHTML = inputText.innerHTML;
  var index = innerHTML.indexOf(text);
  if (index >= 0) { 
   innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);
   inputText.innerHTML = innerHTML;
  }
}

In the above code, we first get the text present in our div element. Then we insert a span element before and after the word that needs to be highlighted. We use indexOf() function to get the starting position of our substring to be highlighted. index+text.length is the ending position of substring to be highlighted. Here text is the substring to be highlighted. Then we update the text inside the div to include span tag with class=highlight.

If there are multiple occurrence of a substring in your text and you want to highlight all occurrences, then it is better to use replace() function, where you replace each occurrence of substring, with the same substring within a span tag with class=highlight. Instead of calculating index of substring, you can use the following code instead.

function highlight(text) {
  var inputText = document.getElementById("my_div");
  var innerHTML = inputText.innerHTML;
  var re = new RegExp(text,"g");
  innerHTML.replace(re,'<span class="highlight">'+text+'</span>');
}

Of course, there are many third party JS libraries that feature out-of-the-box highlight function.

In this article, we have learnt how to highlight text using JavaScript.

Also read:

How to Check File MIME Type With JavaScript
How to Replace Line Breaks with Br Tag in JS
How to Detect When User Leaves Web Page
How to Generate PDF from HTML Using JS
How to Auto Resize IFrame Based on Content

Leave a Reply

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