我试图找到一种方法来突出显示 HTML 中的某些文本。给出了以下 HTML:
<div>This text contains matching words like word1 and word2 and xyzword1xyz and word2xyz and xyzword2</div>
应该被 a 包围的单词列表<span>
是:
var array = ['word1','word2', 'word1word3'];
我当前的 Javascript:
$.each(array , function(index, elem){
if(elem.length<3 || elem === "pan" || elem === "spa" || elem === "span")return true;
var re = new RegExp(""+elem+"(?=([^']*'[^']*')*[^']*$)","gi");
returnString = returnString.replace(re, "<span class='markedString colorword1orword2'>$&</span>");
});
生成的 div 如下所示:
<div>This text contains matching words like <span class='markedString colorword1orword2'>word1</span> and <span class='markedString colorword1orword2'>word2</span> and xyz<span class='markedString colorword1orword2'>word1</span>xyz and <span class='markedString colorword1orword2'>word2</span>xyz and xyz<span class='markedString colorword1orword2'>word2</span> and finally <span class='markedString colorword1orword2'><span class='markedString colorword1orword2'>word1</span>word3</span></div>
由于当前的正则表达式中的所有class='markedString colorword1orword2'
内容不匹配。
问题:如果数组看起来像
var array = ['word1','word2', 'class'];
我最终会得到
<div>This text contains matching words like <span <span class='markedString colorword1orword2'>class</span>='markedString colorword1orword2'>word1</span> and <span <span class='markedString colorword1orword2'>class</span>='markedString colorword1orword2'>word2</span> and xyz<span <span class='markedString colorword1orword2'>class</span>='markedString colorword1orword2'>word1</span>xyz and <span <span class='markedString colorword1orword2'>class</span>='markedString colorword1orword2'>word2</span>xyz and xyz<span <span class='markedString colorword1orword2'>class</span>='markedString colorword1orword2'>word2</span> and finally <span <span class='markedString colorword1orword2'>class</span>='markedString colorword1orword2'><span <span class='markedString colorword1orword2'>class</span>='markedString colorword1orword2'>word1</span>word3</span></div>
这个例子是以某种方式构建的,因此可能有其他词可能存在于 HTML 标记本身中。
我需要一种模拟 regexp-lookbehind 的方法,以便我可以制定如下规则:
匹配不在两者之间的所有内容
<span
,>
但允许级联匹配,例如<span>adsa<span>asdsa</span></span>
是否有任何正则表达式大师知道如何归档?