Javascript RegExp lookbehind

时间:2015-09-16 11:20:13

标签: javascript regex

我有以下问题。我想在Javascript

中的以下字符串中替换“snippet”一词
<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中不可用。

是的,有人能帮帮我吗?

3 个答案:

答案 0 :(得分:-1)

使用先行:

/snippet(?!-expansion)/

REF: https://regex101.com/r/lH5vA3/1

答案 1 :(得分:-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,'')  });

答案 2 :(得分:-1)

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

&#13;
&#13;
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;
&#13;
<textarea id="t" style="width: 500px; height: 200px;"></textarea>
&#13;
&#13;
&#13;