How to Highlight Text in JavaScript

Tahseen Tauseef Feb 02, 2024
  1. Highlight Text Using the searchPrompt Method in JavaScript
  2. Highlight Text Using the Mark Tag Method in JavaScript
How to Highlight Text in JavaScript

If you have always wondered how to highlight text in HTML and thought it would be a complicated task, surprise. In this JavaScript tutorial, this task will be made extremely simple for you.

In this article, we will be learned how to highlight text using JavaScript.

Highlight Text Using the searchPrompt Method in JavaScript

The first method that will be used is to highlight search text through the prompt of JavaScript. You can copy and paste the JavaScript code below on the page. Call the function searchPrompt in the button.

The function searchPrompt uses five parameters. These parameters are explained below:

  1. defaultSearchText sets some text values as default highlighting text.
  2. isPrompt takes two values true and false. The value is set to true if you want to accept the highlighting text value through prompt. Otherwise, it is set as false and will automatically search by default search text value.
  3. treatAsPhrase will be set as true if you want to treat the search text as a single phrase, otherwise, set it as false.
  4. textColor this parameter is optional. The highlighted text color can be set as you want or leave it to default highlighted text color is blue.
  5. bgColor this parameter is also optional. You can set the highlighted background color to what you desire or leave it to default highlighted background color is yellow.

The JavaScript and HTML code for this can be found below:

function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) {
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = '<font style=\'color:blue; background-color:yellow;\'>';
    highlightEndTag = '</font>';
  }

  var newText = '';
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();

  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i + 1);
    if (i < 0) {
      newText += bodyText;
      bodyText = '';
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf('>', i) >= bodyText.lastIndexOf('<', i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf('/script>', i) >=
            lcBodyText.lastIndexOf('<script', i)) {
          newText += bodyText.substring(0, i) + highlightStartTag +
              bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  return newText;
}

function highlightSearchTerms(
    searchText, treatAsPhrase, warnOnFailure, highlightStartTag,
    highlightEndTag) {
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(' ');
  }

  if (!document.body || typeof (document.body.innerHTML) == 'undefined') {
    if (warnOnFailure) {
      alert('the text is unavailable.');
    }
    return false;
  }

  var bodyText = document.body.innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(
        bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }

  document.body.innerHTML = bodyText;
  return true;
}

function searchPrompt(
    defaultSearchText, isPrompt, treatAsPhrase, textColor, bgColor) {
  // we can optionally use our own highlight tag values
  if ((!textColor) || (!bgColor)) {
    highlightStartTag = '';
    highlightEndTag = '';
  } else {
    highlightStartTag = '<font style=\'color:' + textColor +
        '; background-color:' + bgColor + ';\'>';
    highlightEndTag = '</font>';
  }

  if (treatAsPhrase) {
    promptText = 'Please enter the phrase you\'d like to highlight:';
  } else {
    promptText =
        'Please enter the words you\'d like to highlight, separated by spaces:';
  }
  if (isPrompt) defaultSearchText = prompt(promptText, defaultSearchText);

  if (!defaultSearchText) {
    alert('No search terms were entered. Exiting function.');
    return false;
  }

  return highlightSearchTerms(
      defaultSearchText, treatAsPhrase, true, highlightStartTag,
      highlightEndTag);
}
<input style="color:Black" type="button" value="Highlight Text" onclick="return searchPrompt('JavaScript',true,false)" />

You can access this link to watch the working of this code, and you can also play with it. When you run the code above, the following button will appear:

Highlight Button Example

After you click this button, a prompt will appear. You can enter all the words that need to be highlighted in the prompt, giving you your required output.

Output:

JS Highlight Words in Prompt Example

Highlight Text Using the Mark Tag Method in JavaScript

Another method that you can use to highlight the text is the mark tag. If you surround any text inside the mark tag, the browser will automatically highlight it in a striking yellow color.

This word is <mark>highlighted</mark>

This will make highlighting a searched text quite a simple task then. This program is implemented in JSfiddle.

In pure HTML, CSS, and JavaScript, the software takes an input text and highlights the text that you search and mark from the paragraph that you will use as the input text.

Below is an example of how you can implement this program:

  • get the searched text.
  • get the entire text.
  • replace all instances of searched_text with searched_text
  • set the new text as the innerHTML.

Example:

<h1>
    Search and Mark
</h1>

<input type="text" id="search"/>
<button onClick="search(id)" id="button">
Highlight
</button>

<p id="text">
Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications.

Most websites use it for client-side page behavior, and all major web browsers have a dedicated JavaScript engine to execute it. (This excerpt was taken from Wikipedia)
</p>
function search(e) {
  let searched = document.getElementById('search').value.trim();
  if (searched !== '') {
    let text = document.getElementById('text').innerHTML;
    let re = new RegExp(searched, 'g');  // search for all instances
    let newText = text.replace(re, `<mark>${searched}</mark>`);
    document.getElementById('text').innerHTML = newText;
  }
}

Click this link to show the working of the code segment given above.

Output:

JS Before Highlighting Text Using the Mark Tag Example

JS After Highlighting Text Using the Mark Tag Example