[Solved] Wrap words with &nbsp in span [closed]


You can do something like this https://regex101.com/r/bUflp4/2 for you regex. Be care however, it won’t accept tag inside others.


For the replacement, you can use something like this

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>

1

solved Wrap words with &nbsp in span [closed]