I am looking for a way to replace all the words in an HTML string in order to wrap them with tag. I have tried splitting by empty space then iterating through the words and replacing, but the problem is that some words do not start or end with empty space (ex. new paragraph). Maybe there is some kind of Regex that can help or other creative method?
For example let's use the html string:
<h1>Lorem ipsum dolor sit amet</h1>
<p>consectetur adipisicing elit</p>
<p>sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Ut enim ad minim veniam</p>
Here is the code I have so far which is not working good enough:
var html = $("#text").html();
var text = $("#text").text();
var words = text.split(' ');
for (var i = 0; i < words.length; i++) {
html = html.replace(words[i], '<span style="color: red;">' + words[i] +'</span>');
}
$("#text").html(html);
The jsfiddle: http://jsfiddle.net/nd6a3/3/