Real Time Search and Highlight text in JavaScript

Updated: 08-Jan-2024 / Tags: HTML, CSS and Javascript / Views: 329 - Author: George

Introduction

Imagine you have a big article on your website, and you want to give the readers the ability to search for specific terms in it. You also want to add a highlight on the matched term so it will be easier to spot.

You immediately think I can do this using JavaScript, and you are right, but you might not know how. So in this tutorial, we will learn how this is done. We are going to search and highlight text using JavaScript. It's an easy thing to do, and I am going to explain every step so you will easily understand and replicate it on your own and put it on your website.

Now, let's begin.

Live Demo

First of all, I have created a live demo so you can have a first-hand idea of what we are going to code. Start typing in the input field below to see the matching characters get highlighted.

If there is no match, a message is displayed next to the input field that says "Match not found". Try it out.

Project's folder

Let's see the files that we need to recreate the live demo above.

/--project-folder		
  |--index.html
  |--script.js
  |--styles.css
  • Create a project's folder and inside create:
  • An index.html file to write the HTML code.
  • A script.js file to write the JavaScript code.
  • And a styles.css file for our css code.

The HTML code

Let's start our application by writing the html code.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" 
		content="width=device-width, initial-scale=1.0">

	<link rel="stylesheet" href="styles.css">
	<title>Real-Time Search and Highlight in JavaScript</title>
</head>
<body>
	<h2>
		Start typing and see the matching characters 
		getting highlighted
	</h2>

	<div class="search_field">
		<input type="text" 
			onkeyup="highlightSearchText(this.value)" 
			placeholder="Type here..">

		<p class="error"></p>
	</div>
	
	<p class="text">
		JavaScript is a versatile, high-level programming language 
		primarily used for creating dynamic and interactive 
		content on websites. 
	</p>

	<script src="script.js"></script>
</body>
</html>
	

Let's explain the HTML code.

  • The Search Input Field

    The important thing in our HTML code is the input element, which has an onkeyupevent listener assigned. The onkeyup event is a JavaScript event that occurs when a key on the keyboard is released after being pressed. This event is commonly used in web development to trigger actions or functions in response to user input.

    <input type="text" onkeyup="highlightSearchText(this.value)">

    In this line, the onkeyup attribute is set to the value highlightSearchText(this.value), indicating that the highlightSearchText function should be called whenever a key is released.

    The argument this.value will capture the input field's value.

The JavaScript code

Next in the script.js file we are going to write the javascript code.

function highlightSearchText(searchTerm){
	let paragraph = document.querySelector(".text");
	let text = paragraph.textContent;
	document.querySelector(".error").innerHTML = "";

	if(searchTerm.length > 0){
		let regex = new RegExp(searchTerm, 'g');
		let newText = text.replace(
			regex, `<span class="highlight">${searchTerm}</span>`
		);

		if(text === newText){
			paragraph.innerHTML = text;
			document.querySelector(".error")
			.innerHTML = "No match found";
		}else{
			paragraph.innerHTML = newText;
		}
	}else{
		paragraph.innerHTML = text;
	}
}

Now let's explain the highlightSearchText() function.

  • Function Declaration

    function highlightSearchText(searchTerm)

    The code begins with the declaration of the highlightSearchText() function, which takes one parameter: searchTerm. This function will handle the search and highlighting functionality.

  • Select Paragraph Element

    let paragraph = document.querySelector(".text");

    The code selects the paragraph element with the class .text using document.querySelector(). This paragraph element contains the text content that will be searched and highlighted.

  • Get Text Content

    let text = paragraph.textContent;

    The text content of the selected paragraph element is retrieved using the textContent property and stored in the text variable.

  • Clear Error Message

    document.querySelector(".error").innerHTML = "";

    Any existing error message displayed on the webpage (inside an element with the class .error) is cleared by setting its inner HTML to an empty string.

  • Check Search Term Length

    if(searchTerm.length > 0){

    The code checks if the length of the searchTerm is greater than zero. If so, it indicates that the user has entered a search term.

  • Create Regular Expression

    	let regex = new RegExp(searchTerm, 'g');

    A regular expression (regex) is created using the RegExp constructor, with the searchTerm and the global flag 'g'. This regex will be used to find all occurrences of the searchTerm in the text.

  • Replace Matching Text

    	let newText = text.replace(
    		regex, `<span class="highlight">${searchTerm}`
    	);

    The replace() method is used to replace all occurrences of the searchTerm in the text with a highlighted version wrapped in a <span> element with the class .highlight. The resulting text is stored in the newText variable.

  • Check for Match

    	if(text === newText){
    		paragraph.innerHTML = text;
    		document.querySelector(".error").
    		innerHTML = "No match found";
    	}	
    		

    The code checks if the newText is the same as the original text. If they are the same, it means no matches were found, and the original text is restored.

    If no matches are found, an error message ("No match found") is displayed inside an element with the class .error.

  • Apply Highlighted Text

    	else{
          paragraph.innerHTML = newText;
    	}		
    		

    If matches are found, the newText (with highlighted matches) is applied to the paragraph element.

  • Handle Empty Search Term

    }else{
    	paragraph.innerHTML = text;
    }
    		

    If the searchTerm has a length of zero (i.e., if the user clears the input field), the original text content of the paragraph is restored, and the function ends here.

The CSS code

And lastly, we have the CSS code. Copy and paste the following CSS code into your stylesheet to apply the same style and layout that the live demo has.

*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}
body{
	font-family: sans-serif;
	min-height: 100%;
	color: #555;
	background-color: #fff;
	padding: 20px;
}
span.highlight{
	background-color: #beb4ff;
	font-weight: bold;
	padding: 2px;
}
h2{
	margin-bottom: 30px;
	line-height: 40px;
}
.search_field{
	display: flex;	
	align-items: center;
	margin-bottom: 40px;
}
input{
	font-size: 16px;
	padding: 10px;
	border: thin solid #d4d4d4;
	display: block;
	width: 400px;
}
input:focus{
	outline: none;
}
.text{
	line-height: 26px;
	border: thin solid #d4d4d4;
	padding: 20px;
}
.error{
	color: darkred;
	margin-left: 30px;
}

Summary

The tutorial demonstrates how to implement search and highlight functionality using JavaScript on a webpage. It guides users through the process of setting up an HTML input element with an onkeyup event listener to trigger JavaScript code. The JavaScript function, highlightSearchText(), searches for specific terms within text content and highlights them using CSS. The tutorial also provides CSS code for styling the highlighted text. By following the instructions provided, users can enhance their webpages by enabling visitors to search for and visually identify relevant content.

Last words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any errors, so i can update the page with the correct code.

Source code

You can download the source code and use it in any way you like.

Times downloaded: 35

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Comment section

You can leave a comment, it will help me a lot.

Or you can just say hi. 😉