首页 > 解决方案 > 用围绕该单词的 span 标签替换所有出现的单词。不区分大小写

问题描述

我想用 span 标签将所有出现的单词包装在一个字符串中。不区分大小写。并且跨度应该包裹在实际发生的单词周围。而且这个词是可变的。

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.

标签: javascripthtmlstringreplace

解决方案


test您可以通过'gi'作为第二个参数传递给RegExp构造函数来全局匹配单词并忽略大小写。然后$&用来引用匹配的关键字,像这样

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


推荐阅读