JavaScript replace () in upper or lower case

I want to use this function, but preserving upper or lower case, for example, having something like

var value = 'Replace a string';

var search = 'replace';

value.replace(search, "<span style='font-weight: bold'>"+search+'<span>');

And the output of the value will be:

Replace string

+3
source share
2 answers

Since you leave the word itself as is, you can use a simple regular expression:

var value = 'Replace a string';
var search = /replace/i;
value = value.replace(search, "<span style='font-weight: bold'>$&</span>");

$& indicates a matching pattern.

+5
source

Make a searchregex and catch case insensitive "replace" in group:

var search = /(replace)/i;

Then replace the word with a group, inside the tag <span>:

value.replace(search, '<span style="font-weight: bold">$1<span>');
+7
source

All Articles