What are the best ways to emphasize text both inside and outside of tags?

I'm currently working on a WebApp that includes a feature for quick searching articles.

The structure of the feature can be described in two words:

  • Page
  • A global array (json, containing 100-150 items) with articles fetched through ajax. The fields include: id, title, snippet. Titles & snippets may contain simple style markup tags.

When a user types a query in the popup quick search field, the app does the following:

  1. Searches within the global array
  2. If matches are found, they are added to a temporary search results array (with cache)
  3. Highlights the matches in the temp. results array and displays them to the user

It is important to note that the original array remains unmodified.

Currently, I am using basic String.indexOf method, but it cannot accurately match text within HTML-formatted text as shown below:

The question pertains to RegEx patterns. While it is not recommended to manipulate the DOM using RegEx and the expected results may not align semantically, it serves the purpose.

For instance:

<ul><li>Item <i><span style="color:red">Y</span></i></li></ul>

and we want to highlight the letter e, the expected result should be:

... It<em>e</em>m ...
. However, using a simple replace(/e/ig, '<em>$&</em>') will also target the letter 'e' within the style attribute.

In other words, what RegEx pattern can be used to avoid affecting words within HTML tags?


Another example: if we want to highlight Item Y, the desired output would be

<ul><li><em>Item <i><span style="color:red">Y</em></span></i></li></ul>

Answer №1

In order to search for specific text within a portion of a DOM tree, you can use the text contents of XML/HTML. While this example utilizes jQuery, the concept can be adapted for other libraries as well:

Example HTML:

<div id="article_contents">
Blah blah blah, Item 1, Item 2 blah blah <b>Ite</b>m <span>1</span> blah blah
</div>

JavaScript code:

var source = jQuery('#article_contents').text();
var queryRegexp = new RegExp ( 'Item 1', 'g' );
var results = source.match (queryRegexp);

The variable results now contains all instances of the searched string. To further enhance your search functionality by highlighting results, additional steps such as using RegExp.exec to identify match offsets would be necessary.

Answer №2

An unconventional trick is to scan for HTML tags between each letter of the search term. For instance, if your query is "find," the method would be:

(f)(<[.^>]*>)*(i)(<[.^>]*>)*(n)(<[.^>]*>)*(d)

However, in practice, additional steps are necessary because:

  • scripts
  • textareas
  • display:none, visibility:hidden, etc.

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

What is the best way to extract values from a string that are already mapped

Recently, I encountered this string: const string = "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVIC ...

Problem with JQUERY Galleria CSS positioning alignment specifically in Firefox, Chrome works without issues

I recently incorporated jquery Galleria into my website and I am currently facing an alignment issue with the div element gallery-container. Interestingly, it appears correctly aligned in Chrome but is shifted to the right in Firefox. You can view the webs ...

How to extract words from a dynamic router.pathname in NextJS when only the filename is displayed instead of the full path?

I'm keeping this example as straightforward as possible, but I can add more details if needed to solve the issue Currently, I am working with dynamic routes in nextJS. My application fetches data from Twitter based on the keywords entered into the dy ...

Executing multiple commands using Node.js TCP communication

I have established a connection to a serial device via the internet using an ethernet to serial device. The communication is facilitated through a small node.js application. The provided code retrieves the necessary information: var net = require('ne ...

Manage the angularJS user interface switch through an external event

I have implemented an AngularJS Material UI switch and I am looking to update its status based on an external event. This event occurs when a MQTT message is received on a specific topic that is published. To achieve this, I am utilizing a Node.js MQTT cli ...

Unexpected server failure due to a new error occurring in the asynchronous authentication login function

This problem is really frustrating... I'm having trouble with a throw exception that causes my express server to crash in my async login function. The issue here is that the error isn't caught by the try/catch block. Even though the user data is ...

Tips on pausing a moving image from left to right and restarting it later

Is there a way to pause the left to right moving image at the end and then restart the loop? I tried utilizing this website link for assistance: https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_animation-delay Unfortunately, I couldn't fi ...

"Customizable rectangular container with jagged edges created with Scalable Vector Graphics

Currently, I am undertaking a small project that involves creating a box with rough edges around some text. To achieve this effect, I am utilizing an SVG with unique edges similar to the design found at this link: (except mine is in SVG format). My goal ...

Save the value of an AngularJS expression to the clipboard upon clicking

Is there a way to copy the result of the angular expression {{ page.url }} to the clipboard when clicked? I attempted to use ng-clipboard after installing the directive in my project, but it didn't work as expected. <a ng-show="page.hovered" class ...

Activate the submission button on AngularJS once a correctly formatted email is provided

Currently working on an AngularJS demo to better understand its functionalities. The next task on my list is to enable the submit button only when a valid email address is entered. I'm seeking guidance on how to approach this and what concepts I need ...

Troubleshooting Multer to fix image payload issues in a Node.js and React.js application

Currently, I am facing an issue while trying to send an image from my ReactJS frontend to my NodeJS Express backend using formData. Despite seemingly correct data transmission, the image does not appear in the payload and triggers this error from the backe ...

Using Preg Match and Preg Replace for targeted formatting adjustments

I am struggling with understanding how preg_match and preg_replace work, especially when it comes to their elements. Currently, this is what I have: $username = preg_replace('/\s+/', '_', $_POST['uname']); if(preg_match ...

When attempting to render mathML in a canvas on Safari, the image load callback does not properly trigger, resulting in

I am currently working on rendering mathML into an HTML5 canvas. One suggestion I received was to embed the mathML as an SVG foreign object, render it into an image, and then display the image within the canvas. However, this method works fine in Firefox ...

The output of the Javascript expression `["Java", "Python","Javascript"][Symbol.iterator]().next().value` is the initial element of the assigned array

During an interview, I was challenged to retrieve the first value of an array without using an index or any helper functions. The interviewer then provided me with a solution that worked, but I couldn't quite understand how it achieved the desired res ...

Storing checkbox values in a MySQL database using PHP

I am working on a project that involves two checkbox filters. My goal is to keep track of the count of checked checkboxes for each filter and store this information in separate columns in a MySQL table. Could someone please assist me in obtaining the coun ...

Extracting information from JSON structure

My JSON object response includes a `series` array of objects structured like this: { series: [ { name: 'a', data: [1,2,3] }, { name: 'b', data: [4,5,6] } ] } I am looking to extract the `data` values th ...

Utilize jQuery/AJAX to extract a specific value from JSON data and transform it into a different value within the same

Hello everyone, I've been coding all day to try and solve this issue but my code doesn't seem to be working. Can anyone help me with this problem? I'm trying to convert selected JSON data into a different value. Let's take an example: ...

405 error: NGINX blocking POST method in Django DRF Vue.js application

I have encountered a strange issue while building my ecommerce site. Everything seems to be working fine, except for the forms. When attempting to post content, I keep receiving a 405 method get not allowed error. It's confusing as I am trying to use ...

An invalid argument error occurred in line 4618 of jQuery version 1.4.2, with a value of NaNpx specifically

There seems to be a common exception occurring in jQuery.extend as follows: Error Message: Invalid argument. Line Number: 4618 Character Position: 4 Error Code: 0 URI: The issue I am facing is that amongst our development team, only my machine is experie ...

"Exploring the functionalities of Expressjs's bodyParser and connect-form

I am encountering issues when trying to upload images using a connect form. It seems that the bodyParser() is causing problems with the upload process. Conversely, if I do not use bodyParser, I am unable to upload files. How can I resolve this issue and ...