javascript - 带有不区分大小写标志'i'和全局的正则表达式javascript不起作用
问题描述
我正在研究突出显示在字符串中找到的查询文本的方法,这个想法是为找到的每个匹配项添加粗体标记。问题是当我尝试用 g 替换所有出现的查询文本并且 i 标记它没有这样做时,它看起来像是忽略了 i 标记。
这是功能:
highlight = function(text,q){
if (text.indexOf(q) != -1) {
text = text.replace(new RegExp("\\b".concat(q, "\\b"), 'gi'), '<b>' + q + '</b>');
} else{
q = q.split(' ');
q.forEach(function (item) {
if (text.indexOf(item) != -1) text = text.replace(new RegExp("\\b".concat(item, "\\b"), 'gi'), '<b>' + item + '</b>');
});
}
return text;
}
随意测试它,下面是我测试的两个例子:
highlight(' is THIS this','this') => is <b>this</b> <b>this</b>
. 有用 !
highlight(' is THIS','this') => is THIS
. 不
解决方案
尝试这样的事情:
highlight = function(text, q) {
return text.replace(new RegExp("\\b" + q + "\\b", 'gi'),
function(x) {
return '<b>' + x + '</b>';
});
}
推荐阅读
- navbar - 响应式下拉导航栏
- python - 混合类型映射的更强类型注释
- node.js - 在标准输入失败的情况下使用 node-ssh 切换用户
- java - 使用java从url读取json数据
- amazon-web-services - 在单个 fargate 任务中运行多个容器以进行 clair 容器扫描
- windows - Weblogic 服务启动后停止
- mongodb - Golang MongoDB 查找、排序然后插入到另一个集合
- composer-php - 手动安装 phpseclib 的 SFTP 命名空间
- amazon-cloudwatch - Cloudwatch - 消除日志延迟
- maven - 如何解决错误启动应用程序:使用 SWRL API 时创建查询引擎 Drools 时出错?