In my article today, I will show you how you can search for a substring within a string, and how you can build a simple highlighter by searching for an occurrence or multiple occurrences of a string, then replacing it with an HTML tag.
I will break down the processes as so:
- Using the match() method
- Constructing a regular expression
- Performing a case-sensitive search
- Performing a case-insensitive search
Using the match() method
The match()
method matches a string against a regular expression, then returns an array
with the matches or null
if no match is found.
If you provided a string as the search value, it will be converted to a regular expression.
Here's a quick example of using this method.
I have a string, and I want to search for the occurrence of my name in it. Here's how I will use the match()
method to achieve this.
//the string
const str = "My name is simon ugorji";
//using match method on it
console.log(str.match('simon'));
Here's the result
Using the approach above, you are performing a case-sensitive search on the string. If we wanted to search for "Simon" (capitalized), this will be the result.
Null! Because we performed a case-sensitive search and the match was not found.
Instead of passing in a string as the search value, we can also pass in a custom regular expression.
Note that when using regular expressions, you do not have to provide them as a string. This is because the JavaScript engine natively recognizes regular expressions.
//the string
const str = "My name is simon ugorji";
//using match method on it
console.log(str.match(/simon/));
Here's the result
Constructing a Regular Expression
Let's do something a bit different. This time, I will construct a regular expression with the search term and pass it as an argument to the match() method.
To construct a regular expression, we need to use the RegExp constructor function and pass in the string as the first argument and any modifier as the second argument.
//the string
const str = "My name is simon ugorji";
//using match method on it
console.log(str.match(new RegExp('simon')));
Here's the result
Case-sensitive & Case-insensitive search
Without providing the i
modifier, the regular expression performs a case-sensitive search. So this means that using the modifier i
will make the search case-insensitive.
//the string
const str = "My name is simon ugorji";
//using match method on it with the modifier
console.log(str.match(new RegExp('Simon', 'i')));
So I searched for "Simon" (capitalized) and it returned just the result that I need.
Let's Build A Little Function
Just to make sure you understand how to search for the presence of a substring within a string, I will build a function that accepts 2 arguments.
- The first parameter is the search term
- The second parameter is the replacement
The function will perform a case-insensitive search and replace all occurrences of the searched term with its replacement using the replaceAll() method.
While using the replaceAll() method, we need to add another modifier to the regular Expression constructor function g
which means that the regular expression will not stop when it has found the first match of the search term, but will continue to pull up other matches till it has reached the end of the string.
const search = (search, replace) => {
//the string
const str = "I love to eat banana and mango";
//replace all occurrences of the searched term
return str.replaceAll( new RegExp(search, 'gi'), replace );
}
//invoke the function
console.log( search('BANANA', '🍌') );
console.log( search('MANGO', '🥭') );
Here's the result
FINAL FUNCTION
Having understood the basics, we can now build a function that will search through the web page for the presence of a word, then highlight the word if found.
let highlight = (word) => {
//get web page contents
let str = document.body.innerHTML.toString();
//search and replace
str = str.replaceAll( new RegExp(word, 'gi'), `<span style='background-color:red;color:#fff'>${word}</span>` );
//rebuild the webpage
document.body.innerHTML = str;
}
//invoke function
highlight("Simon");
So I have a test web page
This is what the web page looks like when I invoke the function to highlight "Simon".
FINAL THOUGHTS
Here's what to take from my article today.
- You can pass in a regular expression to the match() method and provide any modifier depending on the result you want to achieve.
- Use the
g
modifier, if you wish to find multiple occurrences of the search term. - Use the
i
modifier, if you wish to perform a case-insensitive search. - While using
replaceAll()
method, you must use theg
regular expression modifier
If you're trying to build a bigger HTML highlighter, here are a few tips you need.
- You need to escape special characters
- You need to check for line breaks
Image credit: Estée Janssens on Unsplash
You have reached the end of my article today.
Thank You.