Can you explain how Google highlights the specific search term within the description?

The functionality of my search engine is quite similar to how Google search works. When you search for a word, it gets highlighted in the returned results.

https://i.sstatic.net/Y1vc0.png

In my search engine, the searched word is enclosed in a span like this:

<span class="searchResults-term">Lorem</span>

The input field for entering search queries is very basic:

<input type="text">

The search result descriptions are displayed within this div:

<div class="searchResults-result"> 
   <h3 class="searchResults-title">Lorem Ipsum 
   </h3> 
</div>

I am trying to figure out how to highlight the searched word (e.g., Lorem or Ipsum) in the description based on what the user has typed in the input field. It should not be case-sensitive.

I have been struggling with this issue for hours and have spent an entire day researching solutions. Any help would be greatly appreciated. Thank you!

I have started writing jQuery code for this purpose, but I suspect that my setup may not be correct.

var oldSRTerm = $(".span.searchResults-term").val();

newSRTerm = '<span class="add-pink-bg">' + $(".span.searchResults-term").val() + '</span>',

newSRDesc = $('.searchResults-description').val().replace(RegExp(oldSRTerm,"gi"),newSRTerm);

$('.searchResults-description').html(newSRDesc);

Answer №1

Unfortunately, I don't have the ability to provide comments, and my expertise with JQuery is limited. However, I hope my response proves to be somewhat useful:

To remove case sensitivity, you can utilize the toLowerCase() method.

Implement a condition that checks whether the user's input.toLowerCase() is equal to matchingInput.toLowerCase().

You can make the text bold by adjusting the font style. For example:

$matchingInput.css("font-weight","Bold")

Answer №2

Update:

In my observation, it seems that you are attempting to substitute the .val() of your descriptions. This may not be the correct approach as .val() is typically used for input, 'select`, and other form elements only. Instead, what you should do is extract the "text" of your description first, then proceed with the replacement.

var content = $description.html().trim();

or

var content = $description.text().trim();

Note: The last time I utilized .text(), it was not widely supported, but this information may be outdated.

Other notes:

You can actually incorporate the wrapper within .replace method using RegExp to retrieve the value. This can be achieved by enclosing the search term in parentheses ():

var regex = new RegExp("(" + searchTerm + ")");

content = content.replace(RegExp(regex, 'gi'), '<span class="searchResults-description-highlight">$1</span>');

You can view a working example here: https://jsfiddle.net/tx4nysmk/3/

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

Leveraging multer for handling a FormData object in a node.js server

Having trouble with an HTML form that includes two buttons among other text input areas. The front-end javascript code is set up to handle the submit action by creating a FormData object to store the file and sending it via a jQuery AJAX request to a node. ...

Can someone provide guidance on creating a JavaScript function that locates an image within an <li> element and sets that image as the background-image property in the li's CSS?

Let's dive deeper into this concept: <li class="whatever"> <img src="/images/clients/something.jpg"> </li> <li class="whatever"> <img src="/images/clients/whatever.png"> </li> He ...

Show the Table and Conceal the Overflow

Currently, I am experimenting with creating an Img hover for entertainment purposes. However, I have added some text to my div. In order to center the text beautifully within my div, I utilized the following CSS code: display: table-cell; vertical-align: ...

The attempt to unserializing the configuration schema in Yii2 was unsuccessful

My brain feels scrambled... I am attempting to insert an image in HTML within Yii2. I retrieve it from the database and place it into the view file, but when I try to display it using HTML tags, an error is thrown. However, the image is being added perf ...

The functionality of the WordPress Contact Form 7 Plugin becomes erratic when integrated into dynamically loaded AJAX content

I am currently facing a challenge with integrating the WordPress Contact Form 7 Plugin into a website I have built on WordPress. The theme of the site utilizes jQuery to override default link behavior and AJAX to load pages without refreshing the entire pa ...

Establishing consistent margin and padding for WYSIWYG (What You See Is What You

My webpage retrieves content from a WYSIWYG editor, and I'm looking to apply fixed margins/padding similar to the "h2" element, which always has a margin-bottom of 20px, and paragraphs have a margin-top of 10px. The issue arises when a "p" tag immedia ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

What Could Be Causing the Issue with My Submit Button's addEventListener Function?

At the initial stages of my project, I am encountering a puzzling issue with my addEventListener. Surprisingly, using onClick with the submit button yields the desired results and displays output in the console. However, attempts to implement addEventListe ...

What is the method for closing an <iframe> element directly?

A web page called room.html contains a table with an onclick function named place(): function place() var x = document.createElement("IFRAME"); x.setAttribute("src", "loading.html"); document.body.appendChild(x); } What is ...

What are some ways to implement querySelectorAll in conjunction with htmx?

I'm currently using htmx, an amazing library with a small issue that I'm struggling to resolve. htmx utilizes querySelector to find elements for swapping or updating, for example with hx-swap="...", hx-target="...". How can I use querySelectorAll ...

Image positioned at the top with text links situated at the bottom thanks to Flexbox

I am working on a project that involves placing a flex menu on top of a picture slider. I am struggling to align the items on the same baseline while keeping them on the same line. a img{ height: 40px; } .links{ display: flex; align-items: baselin ...

Warning: Attempting to modify a property that is not defined - 'action'

My code includes a datatable and an alert that pops out. The datatable functions properly with or without the alert, but the alert does not work well when combined with the datatable. Could this be causing a conflict in the code? An error message indicates ...

In Firefox 50.0, the button's resizing feature causes the parent div container outline to adjust size

I am currently working on developing a responsive design with the feature of having a button that appears to "float" under a div element. My desired outcome is achieved in Opera and Chrome: https://i.sstatic.net/Vm55V.png In Firefox, the result is not as ...

Steps to keep the gridlines in the chart from moving

Take a look at the example provided in the following link: Labeling the axis with alphanumeric characters. In this particular instance, the gridlines adjust dynamically based on the coordinate values. How can we modify this so that the chart remains static ...

How can I manage the pageWidth property in the layout of my xPage Bootstrap app?

Check out these two examples - one with app layout and the other with just a navbar, both with fixed pageWidth settings. <xp:view xmlns:xp="http://www.ibm.com/xsp/core" xmlns:xe="http://www.ibm.com/xsp/coreex"> <xe:applicationLayout id="a ...

Transforming JavaScript information into PHP with ajax for WordPress plugin creation

I'm currently navigating the realm of creating my inaugural WordPress plugin and encountering a hurdle in transposing a Javascript array of objects into PHP. My aim is to utilize this data to craft individual tables within the wp-admin user interface. ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...

Concealing the footer on a webpage embedded within an iframe

<script> $(document).ready(function(){ $('.mydivclass').hide(); }); </script> Looking to embed Microsoft Forms in my HTML using an iframe. Can the footer of the Microsoft Forms be removed? ...

Fetching external HTML content and subsequently running a script

Apologies if the title is unclear, I'm having trouble formulating my question. Currently, I'm attempting to use JQuery's ajax load function to load an external html file: $("a").click(function(){ $(".contentWrapper").load(pageURL+" .ex ...

Calculating the product of two input fields and storing the result in a third input field using a for loop

There's a small issue I'm facing. I have implemented a For Loop to generate multiple sets of 3 input fields - (Quantity, Rate, Price). Using a Javascript function, I aim to retrieve the Ids of 'Quantity' and 'Rate', and then d ...