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('([^ ,<]* [^ ,<\/]*)', '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>
1
solved Wrap words with   in span [closed]