javascript - 用围绕该单词的 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.
解决方案
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);
推荐阅读
- python - 如何将本地仓库添加到项目中?
- php - 如何选择每个json数组的内容?
- javascript - 尝试使用 jQuery 从表中提取数据
- c# - MSTest 单元测试控制器
- jekyll - 如何在 Academicpages.github.io 中添加出版物?
- android - androidx.appcompat.widget.Toolbar 似乎有问题
- sql - SUMIF SQL MS 访问
- javascript - 为什么全局对象中的变量未定义,即使它尚未定义?
- c# - 将listview中的内容传输到sql数据库c#
- rest - ServiceNow REST API 左连接或 SQL WHERE/IN 等效项