0

I would like to find a performant and elegant solution to this problem :

I need to replace a substring of a string, case insensitively, by a function of what have been replaced.

Example :

var highlight = function(inputString, filterString) {
    var regex = new RegExp(filterString, 'gi');
    return inputString.replace(regex, '<b>' + filterString + '</b>');
};

highlight('The input', 't');

If your run this in your browser console, you'll get :

"<b>t</b>he inpu<b>t</b>"

My problem is that I'd like to keep the original case of the replaced string. Therefore, the expected result would be :

"<b>T</b>he inpu<b>t</b>"

Any idea ?

Edit: Answer by @georg:

return inputString.replace(regex, '<b>$&</b>');

0

2 Answers 2

5

Just use $& in the replacement, which means "what has been found":

var highlight = function(inputString, filterString) {
    var regex = new RegExp(filterString, 'gi');
    return inputString.replace(regex, '<b>$&</b>');
};

x = highlight('The input', 't');
document.write("<pre>" + JSON.stringify(x,0,3));   

Other $... magic constructs, for the reference:

enter image description here

MDN

Sign up to request clarification or add additional context in comments.

Comments

1

$& contains the string matched by the last pattern match.

Please refer https://msdn.microsoft.com/en-us/library/ie/3k9c4a32%28v=vs.94%29.aspx for more details.

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.