我正在尝试替换字符串中值的所有出现以及另一个值
到目前为止我所拥有的是
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";
我在处理案件时遇到问题,我有什么方法可以忽略这一点并仍然得到我追求的结果
答案 0 :(得分:6)
您需要对不区分大小写的匹配使用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)
答案 1 :(得分:4)
您将使用捕获组和i
(ignoreCase)修改器获得所需的结果。您可以使用$1
引用捕获组。
var result = "Cooker Works";
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function(item) {
result = result.replace(new RegExp(`(${item})`, 'ig'), "<strong>$1</strong>");
});
console.log(result)
&#13;
有关详细信息,请参阅MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
答案 2 :(得分:2)
您需要添加不区分大小写的修饰符。做这样的事情:
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function (item) {
result = result.replace(new RegExp('(' + item + ')', 'gi'),'<strong>$1</strong>');
});
console.log(result);
答案 3 :(得分:1)
这将解决您的问题
Error: The field IceCream.temperature belongs to the record type IceCream.t
but a field was expected belonging to the record type Candy.t