例如,我需要用&nbsp来换行,例如:
<p>Word word and word2? But word word to.</p>
应成为:
<p>Word <span>word and word2?</span> But word <span>word to.</span></p>
我想用JavaScript中的正则表达式来做到这一点。
答案 0 :(得分:0)
您可以为正则表达式执行类似https://regex101.com/r/bUflp4/2的操作。但是请注意,它不会接受其他标签。
对于替换,您可以使用类似这样的
var elements = document.getElementsByClassName("text-to-replace");
for (var i = 0; i < elements.length; i++) {
var innerHTML = elements.item(i).innerHTML;
var regex = new RegExp('([^ ,<]* [^ ,<\/]*)', 'ig');
var text = innerHTML.replace(regex, '<span class="span-to-add">$1</span>');
elements.item(i).innerHTML = text;
}
.span-to-add {
background-color: yellow;
}
<div class="container">
<p class="text-to-replace">Word word and word2? But word word to.</p>
<p class="text-to-replace"> word this is an <a href="#">example</a></p>
<p class="text-to-replace">this is another example</p>
</div>