0

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

1
  • Can you explain with no luck? Commented May 16, 2015 at 19:18

1 Answer 1

1

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>');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.