Scott Becker
Scott Becker

Reputation: 83

In javascript, how do I replace multiple strings with bold text without overriding the previous bold string?

function replaceKeys(inputString, keys){

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

With the javascript method above I have tried to bold all text in a given string, based on a list of "keys" or string parts.

Example inputs:
keys=["man", "str"] inputString="strong man"
intended output:
strong man

Unfortunately the output is replacing the "str" parts of the strong tags too. Meaning the output becomes

<strong>strstrong>ong man.
Is there a Regular expression or some other method so that I can ignore html tags in a string so it doesn't have weird behaviour like this?

Upvotes: 1

Views: 1792

Answers (1)

chrisuae
chrisuae

Reputation: 1112

You can do this by defining a placeholder instead of using <strong> tags directly:

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

Upvotes: 2

Related Questions