gpt4 book ai didi

javascript - 带有不区分大小写标志 'i' 和全局的正则表达式 javascript 无法工作

转载 作者:行者123 更新时间:2023-12-02 23:56:09 28 4
gpt4 key购买 nike

我正在研究突出显示在字符串中找到的查询文本的方法,其想法是为找到的每个匹配项添加粗体标记。问题是当我尝试用 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>';
});
}

关于javascript - 带有不区分大小写标志 'i' 和全局的正则表达式 javascript 无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55381390/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com