I'm trying to surround some words with HTML tags while conserving their case.
for example
let str = "foo key bar Key hello kEY world";
let regex = new RegExp("key", "ig");
the output I'm looking for is something like this
foo <span >key</span> bar <span >Key</span> hello <span >kEY</span> world
I tryed using the replace function but it effects the case
str = str.replace(regex, '<span >key</span>');
Output
foo <span >key</span> bar <span >key</span> hello <span >key</span> world
<!-- all lower case :( -->
I tried this also
let matches = regex.exec(str);
if (matches != null)
matches.forEach(match => str = str.replace(new RegExp(match, 'g'), '<span >' match '</span>');
But some how case is still ignored. Output
foo <span >key</span> bar Key hello kEY world
<!-- only lower case is matched :( -->
is there a way to make something like this
str.replace(regex, the_matched_regex 'some text');
BTW I don't know the possible cases nor the word in advance... I'm making a function to highlight matches of a key in a string ignoring case in search, conserving case in output.
function highlight(src, key) {
/* some code */
return result;
}
CodePudding user response:
You can use an inline function in the 2nd param of the replace
function
let str = "foo key bar Key hello kEY world";
let regex = new RegExp("key", "ig");
str = str.replace(regex, function(match) {
return "<span class='k'>" match "</span>";
});
console.log(str)
CodePudding user response:
You can use a placeholder for the actual match instead of a static string in replace
:
let str = "foo key bar Key hello kEY world";
let regex = new RegExp("key", "ig");
str = str.replace(regex, '<span >$&</span>');
console.log(str)