使用string.replace javascript将子字符串括在span中

时间:2015-05-14 10:23:06

标签: javascript regex str-replace

我有这段代码



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>

函数之前相同

1 个答案:

答案 0 :(得分:0)

您可以在模式后添加负前瞻,以确保我们不会包含另一个span标记。

&#13;
&#13;
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;
&#13;
&#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>