Replace all occurrences of a word with a span tag around that word. Case insensitive

时间:2019-04-08 13:22:19

标签: javascript html string replace

I want to wrap all occurrences of a word in a string with span tags. Regardless of case sensitivity. And the the span should be wrapped around the actual word occurred. And the word is variable.

let title = "TEST word test word Test word tesT";
let regex = new RegExp(keyword, "g");
let titleToDisplay = title.replace(regex, `<span class="searchedTerm">${keyword}</span>`);
//here keyword is 'test' for example. i want to wrap all the occurrences with span.

2 个答案:

答案 0 :(得分:0)

You can match the word test globally and ignoring case by passing 'gi' as the second argument to the RegExp constructor. Then use $& to refer to the matched keyword, like this

let title = "TEST word test word Test word tesT";
let regex = new RegExp(/test/, "gi");
let titleToDisplay = title.replace(regex, '<span class="searchedTerm">$&</span>');
console.log(titleToDisplay);

答案 1 :(得分:0)

You can use "switching words in strings".

Basically, wrap the keyword (whatever it will be) with bracket and use $1 to replace it with the actual founded word.

let keyword = 'test';
let title = "TEST word test word Test word tesT";
let regex = new RegExp(`(${keyword})`, "ig");
let titleToDisplay = title.replace(regex, '<span class="searchedTerm">$1</span>');
console.log(titleToDisplay);