Javascript Js replace和Regex排除一个单词
我对regex有这个问题,它对我来说没有友好的语法:( 基本上,我需要匹配一些文本,并用Javascript Js replace和Regex排除一个单词,javascript,regex,Javascript,Regex,我对regex有这个问题,它对我来说没有友好的语法:( 基本上,我需要匹配一些文本,并用包装匹配的单词/字母 html = html.replace(new RegExp('(' + word + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>'; 返回 "<str<strong>o<
包装匹配的单词/字母
html = html.replace(new RegExp('(' + word + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
返回
"<str<strong>o</strong>ng>Alpinestars</str<strong>o</strong>ng> SMX Plus G<strong>o</strong>re-Tex B<strong>o</strong><strong>o</strong>ts"
“Alpinestars SMX+Gore-Tex Boots”
您很接近。您的订单错了。根据下面的mdn页面,x(?!y)
的意思是:仅当x后面没有y时才匹配x
所以,这似乎对我有用:
var word = 'and';
'dogs <strong>and</strong> cats <strong>and</strong>'.replace(
new RegExp('(' + word + ')(?!</strong>)', 'ig'),
function ($1, match) {
return '<strong>' + match + '</strong>';
}
);
var-word='和';
“狗<强>和猫<强>和<强>”。替换(
新的正则表达式(“(“+word+”)(?!)”,“ig”),
功能(1美元,匹配){
返回“”+匹配+”;
}
);
您可以检查您是否不在元素节点内,并使用(?![^>]*>)
向前看:
函数escapeRegExp(字符串){
返回字符串.replace(/[.*+?^${}()|[\]\\]/g,“\\$&”);
}
var键='o';
var s=“AlpinestarsSMX+Gore-Tex靴子”;
var res=s.replace(RegExp(escapeRegExp(键)+'(?![^>]*>)','ig'),函数(m){
返回“”+m+””;});
document.getElementById(“t”).innerHTML=res.replace(/>/g,”).replace(/ok刚刚尝试过,不幸的是它没有按预期工作。如果单词值为ex的O
,则仍然匹配。(而O
不匹配),我认为您只需要RegExp(word+)(?)?![^@stribizhev看起来更好,但结束标记仍然匹配
请发布输入字符串和其他相关代码以重新编写。我使用@xdhmoore建议添加了一个示例检查我对问题的更新(仍有一些问题)我用对我有用的内容更新了你的答案。(考虑$KEY也可以是一个完整的词……用你的解决方案在这个场景中没有任何匹配)@Wonderland,您的更新被拒绝,因为它完全更改了答案。如果您想共享您的解决方案,请将其作为新答案发布。@Wonderland:如果您需要执行不区分大小写的搜索,请添加i
修饰符。我已将其添加到代码中。
var word = 'and';
'dogs <strong>and</strong> cats <strong>and</strong>'.replace(
new RegExp('(' + word + ')(?!</strong>)', 'ig'),
function ($1, match) {
return '<strong>' + match + '</strong>';
}
);