简体   繁体   中英

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

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.

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); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM