What is the best way to emphasize case-insensitive searchtext matches in JavaScript?

If I have data containing words like Krishna, krishna, KRISHNA and I enter the search text as 'krish', it will retrieve all three words. However, when I want to highlight the matching result, only the exact matching part of the string is highlighted. How can I highlight all matching strings in the given data without considering case sensitivity?

Below is the sample code I implemented:

var searchTxt='KRISH';

var actualTxt='Krish';

if(actualTxt.toLowerCase().indexOf(searchTxt.toLowerCase()){
actualTxt = actualTxt.replaceAll(searchTxt,"<span style='font-weight: bold;background-color: yellow;'>"+searchTxt+"</span>");
}

Please help me with this issue. Thank you in advance.

Answer №1

Here is a code snippet for you to try:

HTML:

<input type="text"/>
<button>search</button>
<ul>
 <li>Krish</li>
 <li>Krish</li>
 <li>Krish</li>
 <li>LastOne</li>
</ul>

JavaScript:

var li = $('ul li'),
input = $('input');

$('button').on('click', function(){
 var search = input.val(), regex;
 li.removeClass('highlight');
 if(search){
   regex = new RegExp(search, 'i')  
   li.filter(function(){ 
    return $(this).text().match(regex);
   }).addClass('highlight'); 
  }
 });

See DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS nested menu functionality not functioning properly

I am currently working on a nested menu item feature in AngularJS. I have a specific menu structure that I want to achieve: menu 1 -submenu1 -submenu2 menu 2 -submenu1 -submenu2 angular.module('myapp', ['ui.bootstrap']) .cont ...

The issue of WithRouter Replace Component not functioning in React-Router-V6 has been encountered

As I upgrade react router to react router v6, I have encountered a problem with the withRouter method which is no longer supported. To address this issue, I have created a wrapper as a substitute. export const withRouter = Component => { const Wrappe ...

Searching and replacing numbers within text using wildcard in PHP string manipulation

After searching extensively, I could not find a straightforward solution for this particular scenario. PHP is not my area of expertise, and I am still in the process of learning. The task at hand involves performing a String Search and Replace operation t ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

Is there a better way to implement an inArray function in JavaScript than using join and match?

Recently, I created an inArray function for JavaScript which seems to be working fine. It's short and a bit unusual, but I have a nagging feeling that there might be something wrong with it, although I can't quite pinpoint what it is: Array.prot ...

Create a placeholder for the module function

Update: Providing more specific details. Our team has developed a Github API wrapper extension and we are looking to test different use cases for it. However, we prefer not to use the API wrapper extension directly during testing and instead want to stub ...

Tips for effectively incorporating customized validation into an array using vuelidate

My array of objects has a specific structure that looks like this varientSections: [ { type: "", values: [ { varientId: 0, individualValue: "" } ] } ] To ensure uniqueness, I implemented a c ...

Exploring nested routes with HashRouter in React

I've been working on a dashboard/admin control panel application using React, but I'm facing some challenges when it comes to handling component rendering accurately. Initially, my main App component is structured like this: <React.Fragment&g ...

How can you prevent the 'Script not responding' error when using Reverse AJAX / Comet?

My worker thread is responsible for sending requests to the server using XMLHttpRequest. The request is directed to a php file which checks the integrity of client information. If the client requires new data, it is sent. Otherwise, the server continuously ...

Tips for showcasing retrieved JSON with jQuery's ajax functionality

Below is the jquery code I am working with: $.ajax({ type: "POST", url: "Ajax/getTableRecord", data:{ i : id, t: 'mylist'}, dataType: 'json', success: function(data){ alert(data); ...

Consecutive pair of JavaScript date picker functions

My issue involves setting up a java script calendar date picker. Here are my input fields and related java scripts: <input type="text" class="text date" maxlength="12" name="customerServiceAccountForm:fromDateInput" id="customerServiceAccountForm:from ...

Is it more efficient to use Vue events or Vuex for transmitting data between components?

Working on a project where data needs to be shared between components in order to update a canvas element at 30-60fps for optimal performance on low-end devices. Currently utilizing Vuex store/get method for data transfer, but considering using events as ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

The button similar to Facebook does not function properly when using fancybox

My photo gallery uses fancybox, and when fancybox is open a like button appears outside the title. However, the Facebook like button doesn't seem to work. Here is my JavaScript code: $(".fancyboxi").fancybox({ padding: 0, openE ...

What is the best way to send form data to MongoDB using React?

I am seeking guidance on how to pass the values of form inputs to my MongoDB database. I am unsure of the process and need assistance. From what I understand, in the post request within my express route where a new Bounty is instantiated, I believe I need ...

Is there a way to instantly remove script from the document head using jQuery instead of waiting a few seconds?

I currently have a setup where I am utilizing Google Maps in production. To make this work, I must include a script in the head of my document that contains the API key for the Google Maps JavaScript API that my application relies on. The API key is being ...

Ensure the browser back button navigates to the login page seamlessly, without displaying any error

A scenario I am working on involves a Login jsp that accepts a user email and sends it to a servlet. If the provided email is not found in the database, the servlet redirects back to Login.jsp with an attribute "error". Within the header of Login.jsp, ther ...

Fixing a binary search algorithm for an array of strings in C: a step-by-step

I developed a C program that is meant to combine 4 string arrays, organize the resulting list, and search for a surname entered by the user. The code successfully executes up until the point of finding the surname; however, it inaccurately reports that any ...

Avoid altering the Vuex store state directly without using mutation handlers in VueJS

I am currently working on developing a listenAuth function that monitors the "onAuthStateChanged" event in firebase to inform the vuex store whenever a user logs in or out. From what I can gather, I am only updating state.authData using the mutation handle ...

Discrepancy in Timestamp Deviation for Older Dates Between Java and Javascript (1 Hour)

When I try to convert a string date representation to numeric values, I noticed a discrepancy between Java/Groovy/PHP and Javascript. Specifically, for certain dates before 1970, the JS timestamp is exactly 3600 seconds behind the Java timestamp. This issu ...