Using an HTML element to pass a variable into a replace function

I am looking to highlight a 'SearchString' by replacing it with

<span style="background-color: yellow">SearchString</span>
within a targetString.

The SearchString varies, so I am wondering how I can make this happen.

This is what I have attempted so far -

var applyHighlighting = function (highlightableElements, productFilterKeyword) {
for(var i =0; i< highlightableElements.length; i++){
    var regexp = new RegExp(productFilterKeyword, 'ig');
    var replaceKeyWord = highlightableElements[i].innerHTML.match(regexp);
    highlightableElements[i].innerHTML = highlightableElements[i].innerHTML.replace(regexp, '<span style="background-color: yellow">replaceKeyWord</span>');
}

Answer №1

If you want to use `$&` in your replacement regex, follow this code snippet:

highlightableElements[i].innerHTML = highlightableElements[i].innerHTML.replace(regexp, '<span style="background-color: yellow">$&</span>');

For more detailed information, visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter


Take a look at this practical example which also stores the original string (an important detail):

var highlightableElements = document.getElementsByTagName('div');
for (var i = 0; i < highlightableElements.length; i++) {
  highlightableElements[i].origHTML = highlightableElements[i].innerHTML
}
var applyHighlighting = function(specificKeyword) {
  for (var i = 0; i < highlightableElements.length; i++) {
    highlightableElements[i].innerHTML = highlightableElements[i].origHTML;
    var regexp = new RegExp(specificKeyword, 'ig');
    highlightableElements[i].innerHTML = highlightableElements[i].innerHTML.replace(regexp, '<span style="background-color: yellow">$&</span>');
  }
}
<input onkeyup="applyHighlighting(this.value)">
<div>Some example text here</div>
<div>Another sample HERE</div>

Answer №2

The issue lies in your replacement string where a variable is used inside it instead of the actual value of the variable. To fix this problem, modify your code as follows:

...
    highlightableElements[i].innerHTML = highlightableElements[i].innerHTML.replace(regexp, '<span style="background-color: yellow">' + replaceKeyWord + '</span>');
} 

By making this change, you should be able to resolve any existing problems.

To simplify the code further, you can refactor it like so:

var applyHighlighting = function (highlightableElements, productFilterKeyword) {
for(var i =0; i< highlightableElements.length; i++){
    var regexp = new RegExp(productFilterKeyword, 'ig');
    highlightableElements[i].innerHTML = highlightableElements[i].innerHTML.replace(regexp, '<span style="background-color: yellow">' + productFilterKeyword + '</span>');
}

If the aim is just to add HTML styling around an existing word, there's no need to complicate by calculating a replacement keyword.

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

Issue with display of Favicon in Google Chrome browser

My favicon is not appearing on my Chrome tab, even though I've checked multiple articles and confirmed that the code is correct. It does show up in Firefox, so I'm confused as to why it's not working in Chrome. I've cleared my cache and ...

Include a scrollbar within a div element nested inside a table cell

index.html <div id="wrapper"> words go here, many of them </div> style.css #wrapper { height: 100%; width: 200px; overflow: auto; } I have been struggling to display the scroll bar on my page, and this is what I am currently exp ...

Analyzing information through jsonParse

After using the command {{$employees}} in my laravel controller to pass data to the blade view, I am receiving the following information: [{"id":"1","name":"june"},{"id":"2","name":"joan"}] When trying to parse this JSON data in my JavaScript as shown be ...

Can I determine if onSnapshot() has detected any updates prior to fetching the data?

While navigating to a page, I pass parameters like "Discounts" and display that number in the render(). However, I call onSnapshot() right at the beginning of navigating to that class. My goal is to initially display only the value of the parameter and the ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...

The JavaScript function's if and else statements are being executed simultaneously

Upon loading the page, I am checking the value of a dropdown. Strangely, when I debug, it appears that the controller is executing both the if and else statements, which should not be happening. /* Here is my code: */ $(window).load(function() { ...

Clicking on a column or x-axis category in Highcharts will automatically include the job number in the page URL

Check out the code I've put together: http://jsfiddle.net/a9QwS/ I'm looking to add functionality where clicking on a column or x-axis label will append its data to the URL. For example, in PHP, I can do something like this: echo " <td sty ...

Experiencing difficulties when establishing a connection between MongoDB and Node.js

I'm encountering an issue when attempting to connect MongoDB and Node.js on my local server. Can anyone assist me with solving this problem? Below is my JavaScript code: const mongodb = require("mongodb"); // Provide the function to connect to the d ...

Struggling to ensure buttons on my page respond and resize properly alongside the other elements

Despite making most of this page responsive, I'm having trouble getting the two buttons to scale appropriately. They are utilizing javascript for a mouseover effect, and I suspect that might be causing some issues. Ideally, I would like the images to ...

Fixing the error: Severity notice, there is an undefined variable called 'table'

My controller logic is as follows: public function index() { if ($this->session->userdata ( 'logged_in' )) { $condition = array( 'qes_status'=>'Y' ); $data = array(); $ ...

How to modify the styling of an input element in React without directly manipulating the input itself

I have collected responses from a survey I created and now I want to showcase the results. The responses are rated on a scale from 1 to 5, and I would like to display them similar to the screenshot. Each number should be presented within a square, with ...

What is the best way to streamline JSON file data by selectively extracting necessary information?

After exporting my user data from Firebase, I am looking to streamline the JSON file by filtering only the necessary fields for my data model. The format of the file obtained from Firebase is as follows: { "Users": { "00uniqueuserid3& ...

Implementing multiple conditions in ng-class for dynamic styling

Is there a way to make both && and || operators work in a single expression like the example below? ng-class = "{'class_name' : condition1 || condition2 || (condition3 && condition4)}" If it is possible, then how can it be implemented? ...

The content loses functionality once I add an overlay color to the background image div

I'm facing an issue with a div that has a background image, text, and a button in the center. Whenever I add an overlay color on top of the background image, the text and button seem to be disabled or unclickable. My goal is to ensure that the Read M ...

Unexpected CSS counter reset issue encountered within nested elements

Utilizing css counters for the formatting of certain wiki pages is a common practice that I implement by adding CSS directly to the wiki page. One particular use case involves numbering headers using counters. Below is a snippet of the code that demonstra ...

What was the reasoning behind Mozilla's decision to implement a conditional catch clause?

Discover the unique Conditional Catch Clauses from Mozilla Delve into this question out of pure curiosity - why would Mozilla venture beyond standard structures with this innovative feature? What specific challenges or issues is it designed to address? W ...

Troubleshooting image alignment problem within a flexbox display

Is there a way to align the two images so that the bottom right of the first image meets the top left of the second image? I'm struggling to figure out a solution, especially considering different browser sizes. Any advice or suggestions? .flexbox ...

The dojo array implemented a new element, pushing out the old one

The JavaScript code below is supposed to populate the array personNames with objects containing names from an array of persons. However, it incorrectly repeats the same name for each object instead of assigning different names: [{"name":"smith"},{"name":" ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

Jquery div mysteriously disappearing without explanation

I need some help with my image options. Whenever I hover over the image, the options appear below it. However, when I try to move down to select an option, they disappear. I have configured the slideUp function so that it only happens when the user moves a ...