Anonymous
Anonymous

Reputation: 1031

Javascript - RegExp in replace return matched string

I have this function that I use to replace the given keywords in a text with the very same keyword but in bold.

function parseKeywords(text){
    var replacedText = text,

        var keywords = getStoredData("currentCrisisKeywords").split(',');

        $(keywords).each(function(i, kw){
            var kWord = kw.replace(/^\s+|\s+$/g, "");
            replacedText = replacedText.replace(new RegExp(kWord, 'i'), '<b>'+kWord+'</b>');
        });
        return replacedText;
}

The problem is that kWord may be "this is a test" while the replaced string was "This is a Test". I need to mantain the original format, while now by replacing it with the keyword, I cannot keep the original format.

I tried this way with no luck:

replacedText = replacedText.replace(new RegExp(kWord, 'i'), "<b>$1</b>");

Do you know a way to return the matched string by mantaining the original format even though the regExp search is case insensitive?

Thanks

Upvotes: 0

Views: 50

Answers (1)

Guffa
Guffa

Reputation: 700592

Put parentheses around the keyword in the pattern so that it is caught, then you can use $1 in the replacement string to use the matched string instead of the keyword:

var kWord = "(" + kw.replace(/^\s+|\s+$/g, "") + ")";
replacedText = replacedText.replace(new RegExp(kWord, 'i'), '<b>$1</b>');

Upvotes: 1

Related Questions