I am trying to find given word in HTML string and add a span around it.
What I am doing now is this:
function find(what:String,where:String)
{
var regexp:RegExp=new RegExp(what,'gi');
return where.replace(regexp,'<span>$&</span>');
}
It works well on words that are not inside HTML tags.
What I want is to ignore those that are inside HTML tags.
Example: find(“spain”)
Input:
The rain in <b class="spain">Spain</b> stays mainly in the <i data-test="Spain">plain</i>.
Output:
The rain in <b class="spain"><span>Spain</span></b> stays mainly in the <i data-test="Spain">plain</i>.
How can I achieve this, please?
To account for html tags and attributes that could match, you are going to need to parse that HTML one way or another. The easiest way is to add it to the DOM (or just to a new element):
Once parsed, you can now iterate the nodes using DOM methods and find just the text nodes and search on those. Use a recursive function to walk the nodes:
Here’s a working demo: http://jsfiddle.net/gilly3/J8JJm/3