How to Highlight the Searched String Result using JavaScript?


Searching for specific content within a large body of text is a common task in web applications. However, simply displaying the search results without any visual indication can make it challenging for users to identify and focus on the relevant information. That's where the need for highlighting the searched string arises. By dynamically highlighting the matching portions of the text, we can improve the user experience and make it easier for users to locate the desired content.

In this blog post, we will explore different methods to highlight the searched string using JavaScript. We'll cover various techniques that range from manipulating HTML content to utilizing regular expressions and CSS styling. Whether you're building a search functionality for a website or working on a text-based application, these methods will empower you to enhance the visibility of search results and provide a more intuitive user interface.

Method 1 - Manipulating the Inner HTML

One straightforward way to highlight the searched string is by manipulating the inner HTML of the element containing the text. This method involves finding the occurrences of the search string within the text and wrapping them with HTML tags or applying inline styles to highlight them visually.

To implement this method, follow these steps −

  • Retrieve the content of the target element where the search is performed.

  • Use the replace() method or regular expressions to find and replace the search string with the highlighted version.

  • Wrap the matched string with HTML tags or apply inline styles to highlight it.

  • Set the modified content back to the target element's inner HTML.

Let's illustrate this with an example. Suppose we have an HTML element with the class name "content" and we want to highlight the occurrences of the searched string within it. We can use the following JavaScript code −

// Get the target element
const contentElement = document.querySelector('.content');

// Retrieve the content
const content = contentElement.innerHTML;

// Replace the search string with the highlighted version
const highlightedContent = content.replace(/search-string/gi, '$&');

// Set the modified content back to the element
contentElement.innerHTML = highlightedContent;

In the code above, we're using the replace() method with a regular expression to find and replace all occurrences of the search string with the highlighted version. The $& in the replacement string represents the matched string itself. We're wrapping it with a element and applying the "highlight" class for styling purposes.

Example 

Here’s how the example would look like −

<!DOCTYPE html>
<html>
<head>
   <style>
      .highlight {
         background-color: yellow;
         font-weight: bold;
      }
   </style>
</head>
<body>
   <div class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Aliquam cursus maximus eros, non consequat nulla vulputate id. 
      Sed porttitor quam a felis viverra lacinia. 
      Vestibulum vestibulum massa at orci ultrices, in maximus tellus aliquam.
   </div>
   <form>
      <input type="text" id="searchInput" placeholder="Search...">
      <button type="button" onclick="highlightText()">Search</button>
   </form>
   <script>
      function highlightText() {
         const searchInput = document.getElementById('searchInput');
         const searchValue = searchInput.value.trim();
         const contentElement = document.querySelector('.content');
   
         if (searchValue !== '') {
         const content = contentElement.innerHTML;
         const highlightedContent = content.replace(
            new RegExp(searchValue, 'gi'),
            '<span class="highlight">$&</span>'
         );
         contentElement.innerHTML = highlightedContent;
         } else {
            contentElement.innerHTML = contentElement.textContent;
         }
      }
   </script>
</body>
</html>

In this example, we have an HTML document with a content div that contains some sample text. We also have an input field for the user to enter their search string and a search button. The highlightText() function is triggered when the user clicks the search button.

Inside the highlightText() function, we retrieve the search string from the input field and trim any leading or trailing whitespace. If the search string is not empty, we retrieve the content of the contentElement using its inner HTML. We then replace all occurrences of the search string (case-insensitive) with the highlighted version using the replace() method and a regular expression. The matched string ($&) is wrapped in a element with the "highlight" class.

If the search string is empty, we restore the original content by setting the inner HTML to the text content of the contentElement.

Method 2: Using CSS Class for Highlighting

In this method, we will utilize CSS classes to highlight the searched string instead of manipulating the inner HTML. Here's how it can be done.

Example 

<!DOCTYPE html>
<html>
<head>
   <style>
      .highlight {
         background-color: yellow;
         font-weight: bold;
      }
   </style>
</head>
<body>
   <div class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Aliquam cursus maximus eros, non consequat nulla vulputate id. 
      Sed porttitor quam a felis viverra lacinia. 
      Vestibulum vestibulum massa at orci ultrices, in maximus tellus aliquam.
   </div>

   <form>
      <input type="text" id="searchInput" placeholder="Search...">
      <button type="button" onclick="highlightText()">Search</button>
   </form>

   <script>
      function highlightText() {
         const searchInput = document.getElementById('searchInput');
         const searchValue = searchInput.value.trim();
         const contentElement = document.querySelector('.content');
   
         if (searchValue !== '') {
            const content = contentElement.textContent;
            const regex = new RegExp(searchValue, 'gi');
            const highlightedContent = content.replace(
               regex,
               (match) => `<span class="highlight">${match}</span>`
            );
            contentElement.innerHTML = highlightedContent;
          } else {
             contentElement.innerHTML = contentElement.textContent;
          }
       }
   </script>
</body>
</html>

In this example, we have defined a CSS class called "highlight" that applies the desired styling for the highlighted text. Inside the highlightText() function, we retrieve the search string, trim it, and retrieve the content of the contentElement using its text content. We then create a regular expression using the search string and the flags 'gi' (global and case-insensitive).

Next, we use the replace() method on the content string to replace all occurrences of the search string with the highlighted version. Instead of using a string replacement, we use a callback function that wraps the matched string in a <span> element with the "highlight" class.

Finally, we set the inner HTML of the contentElement to the highlighted content. If the search string is empty, we restore the original content by setting the inner HTML to the text content.

Method 3: Using Regular Expressions

In this method, we'll leverage the power of regular expressions to dynamically highlight the searched string. Regular expressions provide a flexible and powerful way to match patterns in strings. Here's how we can use regular expressions to highlight the searched string 

Example 

<!DOCTYPE html>
<html>
<head>
   <style>
      .highlight {
         background-color: yellow;
         font-weight: bold;
      }
   </style>
</head>
<body>
   <div id="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Aliquam cursus maximus eros, non consequat nulla vulputate id. 
      Sed porttitor quam a felis viverra lacinia. 
      Vestibulum vestibulum massa at orci ultrices, in maximus tellus aliquam.
   </div>   
   <form>
      <input type="text" id="searchInput" placeholder="Search...">
      <button type="button" onclick="highlightText()">Search</button>
   </form>   
   <script>
      function highlightText() {
         const searchInput = document.getElementById('searchInput');
         const searchValue = searchInput.value.trim();
         const contentElement = document.getElementById('content');
   
         if (searchValue !== '') {
         const content = contentElement.innerHTML;
         const regex = new RegExp(`(${searchValue})`, 'gi');
         const highlightedContent = content.replace(
            regex,
            '<span class="highlight">$1</span>'
         );
         contentElement.innerHTML = highlightedContent;
         } else {
            contentElement.innerHTML = contentElement.textContent;
         }
      }
   </script>
</body>
</html>

In this example, we define a regular expression using the RegExp constructor, passing the search value and the flags 'gi' (global and case-insensitive). We wrap the search value in parentheses to capture it as a group.

Inside the highlightText() function, we retrieve the search string, trim it, and retrieve the content of the contentElement using its inner HTML. We then use the replace() method on the content string, providing the regular expression and a replacement string that wraps the matched search value in a element with the "highlight" class.

Comparison of Methods

Now, let's compare the methods we've covered −

Method 1: Manipulating the Inner HTML

  • Performance  This method is efficient for small to medium-sized texts but may become slower with larger texts due to string manipulation operations.

  • Ease of Implementation  It is relatively easy to implement using JavaScript's built-in string functions.

  • Flexibility  It provides flexibility in terms of customizing the highlighting style and handling case sensitivity.

  • Browser Compatibility  This method is widely supported across modern browsers.

Method 2: Using CSS Class for Highlighting

  • Performance  This method can be slower compared to other methods, especially when dealing with large texts or frequent search operations due to DOM manipulation overhead.

  • Ease of Implementation  It requires a good understanding of DOM manipulation and may involve more complex code.

  • Flexibility  It offers flexibility in terms of customizing the highlighting style and handling case sensitivity.

  • Browser Compatibility  This method is supported by modern browsers, but there might be slight variations in behavior across different implementations.

Method 3: Using Regular Expressions

  • Performance  Regular expressions can be highly efficient for searching and highlighting text, even with large amounts of data.

  • Ease of Implementation  Implementing regular expressions requires a solid understanding of their syntax, which may be more challenging for beginners.

  • Flexibility  Regular expressions offer powerful pattern matching capabilities, allowing for advanced search and highlighting options.

  • Browser Compatibility  Regular expressions are widely supported by modern browsers, but some older versions may have limitations or variations in regex support.

Conclusion

In this article, we explored different methods for highlighting the searched string using JavaScript. Each method has its own strengths and considerations, so it's crucial to evaluate them based on factors like performance, ease of implementation, flexibility, and browser compatibility.

By understanding these methods, you can enhance the search functionality of your web applications and provide a more intuitive user experience.

Updated on: 07-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements