Pattern-matching system for identifying specific words or phrases in a given string in order to facilitate replacement operations

I need help with a coding challenge involving sentences and arrays.

The task is to replace specific words or phrases in a sentence with HTML tags for user interaction. Here's an example using JavaScript:

var sentence = "Yes. I know him from my neighborhood. Come in!",
    phrases  = ["YES", "I", "HIM", "NEIGHBORHOOD", "COME IN"],
    result   = "";

The goal is to wrap each matching word or phrase in the sentence with span tags, allowing users to click on them for more information. The challenge is to do this efficiently within a single loop without relying on regular expressions or additional loops due to potential conflicts with smaller words like "I" or articles like "A" and "AN".

// expected output
result = "<span>Yes</span>. <span>I</span> know <span>him<span> from my <span>neighborhood</span>. <span>Come in</span>!";

Answer №1

If you want to create a dynamic regular expression, you can use the RegExp constructor along with the replace method:

let exampleString = "Yes. I know him from my neighborhood. Come in!",
    wordsToReplace  = ["YES", "I", "HIM", "NEIGHBORHOOD", "COME IN"];

let dynamicRegex = RegExp('\\b('+ wordsToReplace.join('|') +')\\b', 'gi');
let updatedString = exampleString.replace(dynamicRegex, '<span>$&</span>');

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

Save a file in base64 format using Angular's FileSaver for downloading

Currently, I am facing a challenge in downloading a base64 file using angular-file-saver. Previously, I was able to achieve this without angular-file-saver just by using the following HTML code: <a ng-href="data:{{document.mimeType}};base64,{{document ...

Alter the design when hovering over a relevant element

How can I change hover styles for specific items in React? Currently, all item styles change at once when hovered. I want to only change the style of the selected div when hovering over the add to cart button. Visit this link import React, { useState } fr ...

Utilizing *ngIf within a loop to alternate the visibility of table rows with a designated class upon clicking on rows with a different class in Angular 2

I have created a table that displays data, and within this table there are 2 tr elements with the classes default and toggle-row. When I click on a tr element with the class default, it should only toggle the corresponding tr element with the class toggle- ...

Stopping multiple queries in Node.js can be achieved by using proper error handling

Upon verifying the existence of the name, the program continues to the subsequent query and proceeds with inserting data, which results in an error due to multiple responses being sent. How can I modify it to halt execution after checking if (results.row ...

What is the method of aligning content to the left side in a slick slider?

My slider is set up to display three elements, but I'm having trouble aligning one or two elements to the left instead of centering them. jQuery(function () { jQuery('.slider-blog').slick({ arrows: false, dots: true, ...

Tips for utilizing the vuetify readonly prop while enabling the selection menu

In my project, I have a grid containing v-autocomplete components with the multiple attribute. To maintain clean formatting, I decided to show only a shortened version of the content using the selection slot feature provided below: <v-autocomp ...

JavaScript: Harnessing the power of scripts to handle dynamically loaded data via AJAX

I am currently working on a webpage where I need to display various events using AJAX and PHP. One requirement is that when a user clicks on the "view event" link at the bottom of each event, a modal window should pop up. To achieve this functionality, I h ...

NextJs only displays loading animation once

Currently, I am developing an app using Next.js and I am facing a challenge with implementing a loading animation. The animation I am attempting to incorporate consists of three bouncing balls which display correctly. When I launch the Next.js app with n ...

transferring data between two angular modules on a single webpage

Creating several nested modules on a page is something I have done before, for example: module A{ module B{ ..... } } I am wondering if it's feasible to pass values from module A to module B in this setup. I found guidance on how to cre ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

The component data fails to reflect the updated value following a status change due to not properly retrieving the new result from the POST function

Below is the Vue.js 2 code snippet for sending data to the backend. The vuex library was used to manage the data status. After using the POST function, the result returned from the backend updates the value of sampleId. This value is auto-generated by the ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

Working with JSON encoding and decoding for multidimensional arrays in PHP

After encoding an array as JSON and saving it to a database, the structure of the array is as follows: $myarray = array( 'test'=>array('key1'=>'1', 'key2'=>'2', ...

"Regular Expression for Validating Single-Character Multiple-Choice Selection

Hey everyone, I'm a new member here and I'm working on a feature where users have to select one of three choices in order to proceed to the next page "4.html". If they select choice A, they can move forward, but if they don't select any choi ...

Reflection effect on the ground in three.js

Is there a way to achieve the same effect without duplicating spheres? I attempted to replicate the functionality, but the reflections appear too large :/ var groundTexture = THREE.ImageUtils.loadTexture( "files/checkerboard.jpg" ); groundTexture.wrapS = ...

How can we prevent the modal from extending beyond the boundaries of the phone screen when zoomed in

I am currently developing a web application that features a large content page, specifically a map which should display detailed information upon zooming in similar to Google Maps. The interactive elements on my map are clickable, triggering a modal popup ...

Guide on submitting a get form and retrieving the information

Currently, I am employed as a penetration tester for a company. While conducting an analysis of their website, I discovered a vulnerability where CSRF tokens are generated via a GET request to the page localhost/csrf-token and then provided in plaintext fo ...

How can we organize an array with timestamps as keys in descending order?

Can the krsort() function effectively sort an array with timestamp keys in reverse order? Are there any other commonly used functions for achieving this type of sorting? $arr = array(); $arr[1327305600] = '87718'; $arr[1327132800] = '87798& ...

sticky header on pinned tables in a React data grid

I have combined 3 tables together, with the middle table containing a minimum of 15 columns. This setup allows users to horizontally scroll through the additional columns conveniently. However, I am facing a challenge in implementing a sticky header featu ...

What is the best way to transfer parameters from the Vue root to a component?

Currently, I am attempting to transfer a string value from index.cshtml to the main Vue element. The specific parameter I want to pass is: userId Location: Index.cshtml (this is where the parameter is obtained) @using Microsoft.AspNetCore.Identity @inje ...