我有这段代码
52145613

问题是,我想将var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm");
var str = '<div id="rep"> asd 123 asd <span class="new">123</span> asd 123 asd <span class="light">123</span> </div>';
str.replace(rxp, "<span class='highlight' ondragover='event.preventDefault()' ondrop='drop(event)'>$1</span>");
标记在123
标记中,而不是span
,但它还将highlight
和<span class="new">123</span>
括在另一个<span class="light">123</span>
中标记为类span
,例如第一个像highlight
一样包含,而我希望它与<span class="new"><span class="highlight">123</span></span>
答案 0 :(得分:0)
您可以在模式后添加负前瞻,以确保我们不会包含另一个span标记。
var rxp = new RegExp("([0-9]+(\\.?[0-9]+)?)(?![^<]*</span>)", "gm");
var str = '<div id="rep"> asd 123 asd <span class="new">123</span> asd 123 asd <span class="light">123</span> </div>';
document.getElementById("res").value = str.replace(rxp, "<span class='highlight' ondragover='event.preventDefault()' ondrop='drop(event)'>$1</span>");
&#13;
<input id="res"/>
&#13;
输出:
NEW: <div id="rep"> asd <span class='highlight' ondragover='event.preventDefault()' ondrop='drop(event)'>123</span> asd <span class="new">123</span> asd <span class='highlight' ondragover='event.preventDefault()' ondrop='drop(event)'>123</span> asd <span class="light">123</span> </div>
OLD: <div id="rep"> asd 123 asd <span class="new">123</span> asd 123 asd <span class="light">123</span> </div>