What is the best way to replace multiple strings with bold formatting in JavaScript without losing the previous bolded text?

function boldKeywords(inputString, keywords){

    for (var i = 0; i < keywords.length; i++) {
                var key = keywords[i];
                if (key) inputString= inputString.replace(new RegExp(key, 'gi'), '<strong>' + key + '</strong>');
            }
            return s;
}  

Using the JavaScript function above, I attempted to emphasize all occurrences of specific words in a given string based on a list of "keywords" or parts of strings.

For example:
keywords=["man", "str"] inputString="strong man"
Desired output:
strong man

However, the current output ends up replacing the instances of keywords within existing HTML tags as well. This results in

<strong>strstrong>ong man.
Is there a regular expression or alternative method that can be used to ignore HTML tags within a string and prevent this unexpected behavior?

Answer №1

To achieve this, consider defining a placeholder instead of directly utilizing <strong> tags:

function modifyText(inputString, keywords){
    var placeholder = '!!';
    var s = inputString.replace(new RegExp(/strong>/gi),placeholder);
    for (var i = 0; i < keywords.length; i++) {
                var t = keywords[i];
                if (t) s = s.replace(new RegExp(t, 'gi'), '<' + placeholder + t + '</' + placeholder );
            }
            return s.replace(new RegExp(placeholder,'g'),'strong>');
} 
modifyText("strong man",["man", "str"]);

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

Develop a table with dynamic features in Angular according to the number of rows selected from a dropdown menu

I am currently exploring AngularJS 1.6 and tackling the challenge of dynamically populating a table with rows based on the number selected in a dropdown list, ranging from 1 to 12. Here's the code I have up until now: <body ng-controller="myContr ...

The Ajax operation does not finish before the second one is initiated

My Ajax function is set up like this: function PersonAtlLawUpdate(personRef) { var selectionPanel = $('div#SelectionPanel'); var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue; var timeSpan = selectionPanel.fin ...

Reviewing packages often reveals a multitude of mistakes

I attempted to address some issues in my project by executing npm audit fix Unfortunately, this did not yield significant results. However, when I added the --force flag, the outcome was even worse than before: fix available via `npm audit fix` 10 vulner ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. https://i.sstatic.net/ogFA3.png The content provided was considered valid. https://i.sstatic.net/ar5FJ.png An error ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

Problem with clicking on items in Slick Slider Variable width menu once they reach the end

Is there a way to stop the slick slider with variable width items from scrolling after reaching the last item? I am encountering this issue where it continues to scroll even after the end. If you want to see the problem in action, check out this fiddle: h ...

Is it possible to include multiple spyObjs within a beforeEach block?

In the process of testing an Angular 1 application using Jasmine, I have encountered a dilemma. My question is, can two spies be created for two different services within the same beforeEach statement? Currently, I have managed to make the first spy work ...

The Vue router-view is mistakenly loading the parent component instead of displaying its own content

Here is a simple route configuration: { path: '/', component: Home, }, This route configuration sets the path to the home page and loads the Home component when the path is '/'. However, I am encountering an issue where the Po ...

Show only half of the Google Charts

I have a code snippet that displays a chart with dimensions of 500x500. However, I only want to show half of the chart, like 500x250. But whenever I adjust the values in the div, it resizes the entire chart instead of just showing half. My goal is to hide ...

React-Query: executing a function after updating query data

After updating the cache in a form, triggered by a response from the server, I utilize setQueryData. However, following this cache update, my goal is to refocus on the form input field. Here are some details: Within my React application, I employ Recoil. ...

StorageLimit: A new condition implemented to avoid saving repetitive values in the localStorage

Is there a way to store the text of an li element as a localStorage value only once when clicked? If it already exists in localStorage, a second click should have no effect other than triggering an alert. I'm currently using an if statement inside a ...

The tab component is failing to load due to an issue with the Bootstrap tab

I've created a page displaying different locations with two tabs - one for Google Maps and another for weather. For example, take a look at this location: The issue I'm facing is that when switching between the tabs, they don't load fully. ...

Working with ng-model on an array with multiple dimensions

Currently, I am working on storing data in AngularJS. My table consists of various sections, rows, and columns. In each field, there is a dropdown list with the options "O", "T" or "E". My goal is to store these values in an array format: [section][row][c ...

Monitoring and recording user's browsing activities while excluding server-side scripting

Currently, I am working on creating a registration form which will direct users to a "Thank you" page once completed. However, I want to include a button on this confirmation page that will take users back to the previous page they were on before registeri ...

What is the best way to define a default value for a v-text-field in Vuetify within a Nuxt.js project?

As a beginner with vuejs and nuxtjs, I have been introduced to vuetify at my workplace. I am currently trying to set the default value of 0 for v-text-field fields in the application, but unfortunately, I cannot seem to find this information in the vueti ...

alert the Q Promise progress within a Node.js environment

When attempting to utilize the Q Promise Progress feature, my code is designed to catch progress and resolve the Promise once progress reaches 100. Here is the specific code snippet: var q = require("q"); var a = function(){ return q.Promise(functio ...

Incorporate the slick-slider functionality smoothly into a WordPress website by utilizing JavaScript

I am fairly new to .js and currently attempting to incorporate a .js slider into my Wordpress site. I have been working on getting Slick-Slider operational on a website. While it functions perfectly fine on my static webpage, the transition to Wordpress ha ...

Vue component failing to display data passed as props

As a Vue beginner, I ventured into creating a custom component and attempted to bind everything just like in the basic Vue CLI template. Here is my code snippet. Circle.vue <template> <div :style="custom"> </div> </template&g ...

What is the best way to dynamically assign a value to an anchor tag upon each click using jQuery?

How can I pass a value to an anchor tag on every click using jQuery? I am encountering an issue with my current code where the value is not being retrieved when I click the button. //HTML snippet <button id="a-selectNm" data-a_name="<?php echo $row[ ...

Continuous polling with Ajax in Rails does not trigger the display of an alert box

Trying to implement ajax polling using the RailsCast tutorial on ajax polling (#229) but encountering an issue where the alert box doesn't pop up after running the server. Here's the code in app/views/quotes/index.js.erb: alert('Hey') ...