我正在尝试用另一个值替换字符串中所有出现的值
我目前的情况是
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function (item) {
result = result.replace(new RegExp(item, 'g'), "<strong>" + item + "</strong>");
});
console.log(result)
我想要的结果应该是这样的
result = "<strong>Cooker</strong> <strong>Wor</strong>s";
我在处理这个案子时遇到了问题,有什么办法可以让我忽略它并仍然得到我想要的结果
最佳答案
不区分大小写匹配需要使用i
修饰符
new RegExp(item, 'ig')
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function(item) {
var matchs = result.match(new RegExp(item, 'ig'));
if (matchs.length)
result = result.replace(new RegExp(item, 'ig'), "<strong>" + matchs[0] + "</strong>");
});
console.log(result)
关于JavaScript 替换所有忽略大小写敏感,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44905159/