Highlight keywords in a text area
Tags: tutorial, javascript, webdev
Published: 2023-12-18 02:49:10

If you're building a website or application that includes a text area, you might want to give users the ability to highlight specific keywords within that text. This feature can be helpful for various reasons, from finding important information to navigating a large block of text with ease.

In this post, we'll learn how to implement this functionality using JavaScript. Are you ready to get started?

## Highlighting the keyword with the mark tag

To highlight a specific keyword in a block of text, the easiest approach is to find all instances of the keyword and replace them with a highlighted version. Here's an example of how you might do this:

```js
// Get the text area element
const textarea = document.getElementById("textarea");

// The keyword to highlight
const keyword = "example";

// Create a regular expression to match the keyword
const regex = new RegExp(keyword, "gi");

// Replace the keyword with a highlighted version
textarea.value = textarea.value.replace(regex, "<mark>$&</mark>");
```

In this example, we're using the `getElementById` method to get the text area element. We then create a regular expression to match the keyword and use the `replace` method to replace all instances of the keyword with a highlighted version wrapped in a `<mark>` tag.

The `replace` method returns a new string with all occurrences of the regular expression replaced with the specified substring. The `gi` flag in the regular expression stands for "global" and "case-insensitive", meaning that all occurrences of the keyword will be matched, regardless of their case.

> The `<mark>` tag is an HTML element used to highlight text. By default, most browsers display highlighted text in yellow, but you can customize this using CSS. The tag is commonly used to draw attention to specific words or phrases within a block of text, making it easy for users to quickly identify important information on a page. Additionally, search engines may use the `mark` tag as a signal that the highlighted text is relevant to a user's search query.

The approach may seem promising in theory, but it doesn't actually work. This is because the text area element treats its value as plain text, even if it includes HTML tags. So, even if we add a `<mark>` tag to highlight a keyword, it won't show up as highlighted within the text area.

## Emphasizing the keyword in the mirrored element

To solve this issue, we'll replace the text area with a new `div` element that has the same content and position. Then, we can replace the HTML of the new element to make the highlighting work properly.

To replace the keyword within the mirrored element, we can use the approach mentioned at the top:

```js
const regexp = new RegExp(KEYWORD, 'gi');
mirroredEle.innerHTML = textarea.value.replace(regexp, '<mark class="container__mark">$&</mark>');
```

Each mark has an additional class named `container__mark`, which customizes the look and feel of the highlighted element instead of using the default appearance of the browser:

```css
.container__mark {
    background: rgb(253 224 71);
}
```

To ensure that our highlighting functionality works as expected and maintains visual consistency with its original source, we need to add an additional CSS class to the text area element:

```css
.container__textarea {
    background: transparent;
}
```

To make sure that the highlighted keywords are visible and don't blend in with the background, the text area element's background color must be transparent. Otherwise, users won't be able to see the highlighted text because it will be hidden behind the text area element.

Let's take a look at the result.

{% codepen https://codepen.io/phuocng/pen/eYxqWLw %}

As you can see, all instances of the word 'you' are highlighted. However, there is an issue. If you update the text area content, the highlighted words won't be updated. Don't worry though, we'll tackle the issue in the next section.

## Highlighting text when the value of the text area changes

To address the first issue we mentioned earlier, we can handle it by using the `input` event. This event is triggered when the user changes the value of the text area. In the event handler, we will replace the keyword to highlight it.

Here is an example of what the `input` event handler looks like:

```js
const regexp = new RegExp(KEYWORD, 'gi');

const highlight = () => {
    mirroredEle.innerHTML = textarea.value.replace(regexp, '<mark class="container__mark">$&</mark>');
};

textarea.addEventListener('input', () => {
    highlight();
});
```

Let's check out the final demo of the steps we've been following.

{% codepen https://codepen.io/phuocng/pen/dyaxWgO %}

---

It's highly recommended that you visit the [original post](https://phuoc.ng/collection/mirror-a-text-area/highlight-keywords-in-a-text-area/) to play with the interactive demos.

If you found this series helpful, please consider giving the [repository](https://github.com/phuocng/mirror-a-text-area) a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

-   [Twitter](https://twitter.com/_phuocng)
-   [GitHub](https://github.com/phuocng)