DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for How To Build A Simple HTML Highlighter with JavaScript
Simon Ugorji
Simon Ugorji

Posted on

How To Build A Simple HTML Highlighter with JavaScript

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'));
Enter fullscreen mode Exit fullscreen mode

Here's the result

image.png

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.

image.png

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/));
Enter fullscreen mode Exit fullscreen mode

Here's the result

image.png

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')));
Enter fullscreen mode Exit fullscreen mode

Here's the result

image.png

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')));
Enter fullscreen mode Exit fullscreen mode

So I searched for "Simon" (capitalized) and it returned just the result that I need.

image.png

Let's Build A Little Function

Just to make sure you understand how to search for the presence of a sub-string 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', 'πŸ₯­') );
Enter fullscreen mode Exit fullscreen mode

Here's the result

image.png

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");
Enter fullscreen mode Exit fullscreen mode

So I have a test web page

image.png

This is what the web page looks like when I invoke the function to highlight "Simon".

image.png

Here's the code in action on codepen

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 the g 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.

Top comments (0)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!