Matching text highlight on search using html and js

  • 16-12-2022
  • 490
  • Jquery
  • Haresh Chauhan

javascript highlight matching text when you search from the input, below I have given an example of how to search or filter data from the server and return a response data string, it will highlight match your search data in the dropdown and will show you matching string as the given color highlight.

Using the javascript customer-made function we will Find and highlight a word in text using JS, this function was logically made by me after a long try apply during making this function.

So if you are looking for How to highlight search text in HTML with the help of js? this post will help you with the example function just follow the below given example and apply to your website very quick.

This example searches and highlights text on the page while keeping the search in the input field using js or jquery and ajax.

Preview :

Code Example

This is the input field given with the search id, this input field engages with the jquery event which is keyup even. so when the user searches text in this input it will go to the server and find a matching string from the server and highlight that matching string at that search moment.

<input type="text" id="search" name="search" class="header-popup-modal" placeholder="Search Our Store...." autocomplete="off" />
<div id="head-append" class="pt-2"></div>

Below given a highlight() function this function will return a string with matching search text and also with the given full text.

<script type="text/javascript">

function highlight(highlight,string){
  var index = string.toLowerCase().indexOf(highlight.toLowerCase());
  if (index >= 0) {
    return string.substring(0,index) + "<span style='color: orange';>" + string.substring(index,index+highlight.length) + "</span>" + string.substring(index + highlight.length);
    return string;

    var search = $(this).val();
        type: "GET",
        url: "{{route('search.product')}}?search="+search,
        success: function (response) {
            $('#head-append').html(' ');
            $.each(, function (key,val) { 
                var urls = "{{env('APP_URL')}}"+val.slug;
                $('#head-append').append('<a style="text-decoration:none;color:black;" href='+urls+'>'+ highlight(search, +'</a></br>');

We always thanks to you for reading our blogs.


Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us


Haresh Chauhan


We Are Also Recommending You :