繁体   English   中英

Javascript RegExp 回顾

[英]Javascript RegExp lookbehind

我有以下问题。 我想用 Javascript 替换以下字符串中的“片段”一词

<p>This is a <span class="snippet-expansion">snippet<span><p>

但我想保留 class="snippet-expansion"。

另一种情况可能是

<p>This is a snippet within a text<p>

第二种情况的结果应该是

<p>This is a <span class="highlight-searchterm">snippet</span> within a text<p>

通常,我会在正则表达式中使用lookbehind来做到这一点,但这些在Javascript中不可用。

有人可以帮助我吗?

与前瞻一起工作:

/snippet(?!-expansion)/

参考资料: https : //regex101.com/r/lH5vA3/1

试试这个表达

var str='<p>This is a <span class="snippet-expansion">snippet<span><p>';

str.replace(/snippet.*?(\W|\s)+/g,function (val){ if(val.trim().match(/\W+/g) && !val.match(/</g)) return val; return val.replace(/snippet/g,'')  });

在结束标记>和开始标记<之间查找文本应该适合您的情况。

 var str = '<p>This is a <span class="snippet-expansion">snippet<span><p>'; var rep = str.replace(/(>[^<>]*)snippet([^<>]*<)/, "$1foo$2"); document.getElementById("t").value = rep; document.getElementById("t").value += "\\n\\n"; var str1 = '<p>This is a snippet within a text<p>'; var rep1 = str1.replace(/(>[^<>]*)snippet([^<>]*<)/, "$1foo$2"); document.getElementById("t").value += rep1; document.getElementById("t").value += "\\n\\n"; var str2 = '<p>This is a <span class="highlight-searchterm">snippet</span> within a text<p>'; var rep2 = str2.replace(/(>[^<>]*)snippet([^<>]*<)/, "$1foo$2"); document.getElementById("t").value += rep2;
 <textarea id="t" style="width: 500px; height: 200px;"></textarea>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM