JavaScript Search and Highlight Words within String
We have many times observed the yellow highlight around the string and as a programmer tried to think how can it possibly be able to mark all search words in a document that too in split milli-seconds. And after crawling the web and going through posts written by high skilled and experienced programmers I was able to achieve this goal. In this post will be on using regular expressions in highlighting the searched patterns inside the string.
Table of Contents
Introduction
Before this, we have done posts on string searching and replacing string which selective words. But this post is different from the rest of those as we’ll not only search but also, highlight searched words.
Using RegEx object
Regular expressions are a great way to get the desired output from matching words in a string. In javascript, we can create regular expression object using RegExp
a class which takes pattern and flags as an argument.
Syntax
new RegExp(search_pattern, search_flags);
- search_pattern: These include regular expression characters for searching in strings.
- search_flags: In Regular Expression, flags act as a configuration which will determine the result or output.
Some of the flags are given below:g (global match)
: This flag finds matches throughout the string.i (disregards matched character or word case)
: This flag will ignore the case of the matched string.
Create a simple search using RegExp
let string = "The best way to cheer yourself up is to try to cheer somebody else up."; let pattern = 'self|body', flags='gmi'; let new_regexp = new RegExp(pattern, flags) console.log(new_regexp.exec(string)); console.log(string.match(new_regexp)); // Console Output ["self", index: 26, input: "The best way to cheer yourself up is to try to cheer somebody else up.", groups: undefined] (2) ["self", "body"]

Searching within a string using RegEx in Javascript
The new_regexp
is an object created using class RegExp
. Using the method .exec()
we can check if the pattern exists in a string.
If a pattern exists that array is returned and if does not exists then null
is returned.
Highlighting searched words
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <style> #search_text{ height: 30px; width: 200px; } </style> </head> <body> <p id="sentence" >There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p> <input onkeyup="hightlightSearchResult()" id="search_text" type="text" placeholder="Search..." value="" > <script type="text/javascript" > let sentence_element = document.getElementById('sentence'); let search_text_element = document.getElementById('search_text'); let sentence_element_html = sentence_element.innerHTML; function hightlightSearchResult() { let search_text_value = search_text_element.value; search_text_value = search_text_value.replace(/[.*+?^${}()|[]\]/g, '\$&'); //https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex let regex_object = new RegExp(search_text_value, 'gi'); if (search_text_value.length > 0){ sentence_element.innerHTML = sentence_element_html.replace(regex_object, `<mark>$&</mark>`); }else{ sentence_element.innerHTML = sentence_element_html; } } </script> </body> </html>

Search and highlight words in Javascript
Function hightlightSearchResult()
is triggered on keyup
event. regex_object
is a regular expression object
which we can use to check searched_text_value
exists in the paragraph.
Note
$&
in regular expression get the lastMatch of searched value.
Conclusion
We have come to the end of our post on JavaScript Search and Highlight Words within String. If you like our content then please do share it and comment to clarify your doubts.
Related Posts
- JavaScript Tips for Array Looping and Iteration for Beginners
- JavaScript | Accessing and Manipulating DOM Elements for Beginners




