用跨度的单词换行

时间:2018-08-14 12:18:27

标签: javascript regex

例如,我需要用&nbsp来换行,例如:

<p>Word word&nbsp;and&nbsp;word2? But word word&nbsp;to.</p>

应成为:

<p>Word <span>word&nbsp;and&nbsp;word2?</span> But word <span>word&nbsp;to.</span></p>

我想用JavaScript中的正则表达式来做到这一点。

1 个答案:

答案 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('([^ ,<]*&nbsp;[^ ,<\/]*)', '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&nbsp;and&nbsp;word2? But word word&nbsp;to.</p>
  <p class="text-to-replace">&nbsp;word this is an&nbsp;<a href="#">example</a></p>
  <p class="text-to-replace">this is&nbsp;another&nbsp; example</p>
</div>