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

What is the process for unit-testing a compiled template with the "controller as" approach?

I have been trying to unit test my controller with a template. I found that it works fine if everything is linked to $scope. However, when I switched to using the "controller as" syntax, the test stopped working. It makes sense since now everything is tied ...

The program encountered an issue: Initialization must be completed before utilizing hooks

I'm facing an issue with my new Next app. I added line no. 6 and now I'm getting an error. Can anyone help me understand why? import Head from "next/head"; import Image from "next/image"; import styles from "../styles/H ...

Tips for preserving user input from HTML into a text file and then reloading it back into the HTML document

I have recently created a character sheet for a game using HTML. The HTML file is mainly comprised of various input tags such as <input type="text">, <input type="number">, <input type="checkbox">, <input type="radio">, <select&g ...

divs aligned vertically on opposite edges of the webpage

Our web app is being embedded in a third party page as an iframe, but we need to add a bottom "toolbar" with 2 links. One link should be plain text and the other should display our company logo preceded by some text. We want the two links to be positioned ...

Having trouble using Selenium for Chrome to locate an element in an HTML file using C#?

I am currently utilizing Selenium to locate elements within an HTML document that is being displayed in the Chrome browser. Unfortunately, the HTML code is not created by me and appears to have numerous issues. I do not have the ability to modify how it is ...

Utilizing reusable functionalities within Vuex

Currently, while working on my NUXT project, I am facing a situation where I find myself repeatedly copying the same actions into multiple store modules. To streamline this process, I have extracted these actions into a separate file and now import them in ...

Using Jquery Functions within Codeigniter

I am facing an issue with calling a function containing jQuery script within an if-else statement. Below is the codeignitor view code: Code if($osoption == "windows") { ?> <script> windows(); </script> <? ...

Is it time to use JQuery post-DocumentReady?

After all the $(document).ready scripts have run, is there a way to register an event that will be executed? I have code that must run after the entire page, including jQuery scripts, has finished loading. Is this achievable? I have to register this in a ...

difficulties arise when adjusting font size in html and css

When I first created an all HTML/CSS website, I used clickable images as a menu that scaled perfectly on all monitors and browsers. Now, for my new project, I wanted to use a background image for the menu with hyperlinked text on top. I thought setting the ...

Are the functionalities of my code implemented with Node.js and callback functions comparable to Java Threads?

I am unfamiliar with the Node.js concurrency model. Below is an example of creating Java threads and starting them concurrently. package com.main; class MyThread implements Runnable{ private int num = 0; MyThread(int num){ this.num = num; } ...

Tips on saving additional parameters in an API URL with AngularJS

Here is my AngularJS function code: $scope.cardcall = function (cardtype) { $scope.cityname=cityname; $http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(funct ...

The element is unclickable due to being obstructed by another element

My task is to click on a button using this code: browser.find_element_by_id('btnSearch') However, the button is being blocked by a div tag with the following attributes: <div id="actionSearch" class="row pull-right"> How can I work around ...

Need help automating clicking the download csv button with Selenium Python, but the button's class name changes when it's hovered over?

While attempting to save a csv file by clicking the download csv button on a website, I encountered an issue. It seems that the .click() action is not functioning as expected, and upon inspection, I noticed that the class-name of the button changes from &a ...

Retrieve data from HTML in order to apply styling to an element

I am attempting to set the width of my .bar-1 outer span element based on the value of my inner span element. <span class="bar bar-1"> <span name="PERCENTAGE" id="PERCENTAGE" disabled="" title="Total Percentage" maxlength="255" value="66" tabinde ...

The variable $ has not been defined in Jquery framework

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="deployJava.js"></script> <script type="text/javascr ...

Enhancing User Experience with CSS Transitions for Faster Page Loading

Recently, I stumbled upon a captivating website that has left me in awe - . The mesmerizing aspect of this site lies in the seamless and fluid animations that gracefully transition when navigating between pages. I find myself yearning to understand the int ...

What is the best way to reach nested iframes?

I am looking for a solution to send post messages (window.postmessage) to iframes. Currently, it is functioning properly with a single iframe inside the parent page. However, I want it to also work for nested iframes. Here are the criteria: I should on ...

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

Conceal an element along with its space, then signal the application to show alternative content using React

Greetings everyone! I seek assistance with a React Application that I am currently developing. As a newcomer to the Javascript world, I apologize if my inquiry seems trivial. The application comprises of two main elements: a loader, implemented as a React ...