Using jQuery to dynamically create multiple span elements from an array of strings

I have a software application that is designed to identify key words and apply CSS highlighting to them.

Utilizing jQuery for this purpose, my goal is to enable users to customize which words are highlighted.

The issue I'm currently facing is not the lack of highlighting (good news), but rather the inconsistency in the highlighting process (bad news). Although I have specified certain words to be colored (such as balloon, Dorothy, cyclone), sometimes these words are not all or none are correctly highlighted.

Hopefully, looking at this example on jsFiddle will provide better clarity than my explanation. As shown by the second line, the first word and keyword, Dorothy, remains uncolored when it should be red.

Thank you in advance for your help. Please excuse any confusion in my message, and feel free to share your feedback!

Answer №1

Do you find this satisfactory?

$(function(){
     var keywords = new Array("Dorothy","cyclone","miles","house","balloon");
     var regex = new RegExp(keywords.join("|"),"g");
     $('#oz li').html( function(i,value){
          return value.replace(regex,
               '<span containsStringImLookingFor="true" id="$&">$&</span>');
     });
});

Explanation

regex is

/Dorothy|cyclone|miles|house|balloon/g
, a regular expression that matches all the words in your array. The .replace() method replaces all matched words with '
<span containsStringImLookingFor="true" id="{matched word}">matched word</span>
' template. '$&' indicates the current matched word.

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

Ajax request unable to load Image Slider

I'm currently implementing an Image Slider from this source For the site structure, I've set up an index.html file to display all the pages, allowing navigation by changing the content within <div id="isi">. Here's a snippet of the in ...

CSS Interactive Design Breakpoints

Do my Break points at 768, 480, and 225 provide enough support for a responsive design, or should I consider adding more? 768 + | Computer 480 - 768 | Tablet 225 - 480 | Smartphone 225 < | Phone / Mini Browser ...

JS script for clicking various icons on a webpage that trigger the opening of new tabs

I am working on a webpage where I have 9 icons with the same class. I am trying to write JavaScript code that will automatically open all 9 icons when the webpage loads. I tried using the code below, but it only clicks on the first icon and stops. let ...

How can you access Python variables within an AJAX success callback?

How can I access Python variables in an AJAX success call? I am sending data from HTML form inputs to a Python backend using an AJAX post call. In the AJAX success callback, I need to use Python variables to dynamically create the <tbody> of an HTML ...

Issue arises during initialization with Slick.js

I recently attempted to implement the slick.js function on my webpage by following the guidelines provided on . I copied the "center mode" function as my Jquery function, but unfortunately, the arrows/buttons and nav-docs were not generated in my slideshow ...

Determining the element type that was clicked using Angular

Is there a way in Angular to determine the type of element that was clicked? I have successfully implemented this functionality using jQuery, but I'm unsure how to achieve the same outcome in an Angular project. // Click action $(".contactlist").on(" ...

I am currently attempting to execute an HTML file in VS Code, but encountered an issue with the following error message: "Sorry, we can't find your file. It may have been relocated, modified, or removed."

I am trying to work on a Hello World HTML file, but for some reason I cannot find the file even though I have it opened from Ubuntu. As I am new to coding, I am struggling to figure out what's going wrong. <!DOCTYPE HTML> <HTML> <head& ...

JavaScript - determine the sum by utilizing dynamic variables

Looking to streamline the calculation of a total price based on toggling checkboxes for various price components. Here is the code logic currently being utilized: comp1 = 100 comp2 = 200 comp3 = 300 totalPrice = -> if $('#checkboxA').h ...

Choosing a root element in a hierarchy without affecting the chosen style of a child

I am working on a MUI TreeView component that includes Categories as parents and Articles as children. Whenever I select a child item, it gets styled with a "selected" status. However, when I click on a parent item, the previously selected child loses its ...

Flask does not display images in CSS files

Starting with the frontend (HTML, CSS) of my project, I then proceeded to create a Flask file with the following code: from flask import Flask, render_template app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): return render_templa ...

Implementing functionality: Removing a row and applying a CSS class upon button click

Check out the fiddle below: https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/ I need help with creating a remove function and adding a CSS class to a clicked row. 1. When I click on "remove", the clicked row should be deleted. When I click on a row, ...

The alignment of flexNav.js submenus is not consistent

I'm looking to implement the Flex Navigation plugin for a responsive menu. Although the plugin functions properly, I'm encountering an issue with the alignment of submenus under their respective parent items. You can view the problematic behavi ...

Align three divs vertically within one div, all floated to achieve the desired layout

Can someone help me align three divs vertically within a container div? The challenge is that all three divs inside the container are floated - one on the right, one in the center, and one on the left to create a navbar. I've seen the navbars in Boot ...

The attempt to follow or favorite the item at http://127.0.0.1:8000/follow/fav/8/1/ has resulted in a 403

I can't figure out why this error keeps happening. I have a favorite app, and it seems like the ajax functionality is breaking down. The error occurs when I click a button that should be working but isn't functioning properly at the moment. My su ...

What is the best way to ensure that my button only reveals the corresponding div in its group upon clicking?

Currently, when I click the first button, both hidden divs are showing. I want it so that when I click the first button, only the hidden div in its group is shown. Similarly, when I click the second button, only the hidden div in its group is shown. Can s ...

The controller argument for Ajax data object is found to be empty

Currently, I am attempting to make an ajax call to a controller method that accepts an object. The code I have at the moment is as follows: [HttpPost] public ActionResult EditStudent(Student student) { //do something } Here is the Ajax call I am us ...

Tips for detecting the height of a row with 2 columns in CSS

I am attempting to create two text/image boxes side by side, where one box dictates the height of both on desktop. In this scenario, the leftcol box should expand its background color to match the size of rightcol and center the content. On mobile devices, ...

Animating splitting elements with VueJS

I am facing a challenge in creating a split animation with two icons. My goal is to split the icons with some translation in the X-axis after hovering on the container, but it seems like I am missing something in my implementation. The animation does not w ...

The image tag is being used to show the exact location, however, there is no

How can I load a previously uploaded image via ID in the controller? The controller passes the correct location to the view, but the view does not display the image. When I inspect the view page, it shows the correct ID and location but does not render the ...

Experience running two functions simultaneously in jQuery simulation

Presented here are two functions that I am working with: loadTop(); loadBottom(); One of these functions is responsible for loading the top portion of a page while the other takes care of loading the bottom. The loadTop function involves asynchronous o ...