var target = $(".target-text"),
relation = ['spun gold', 'gold', 'apple'],
len = relation;
for (var i=0; i<len; i++) {
var e = relation[i],
re = new RegExp(e,"ig");
if (e.length > 0) {
target.html( target.html().replace(re, "<span class='hit'>$&</span>") );
}
};
The searched characters are surrounded with a tag.
At this time, There is a problem.
The problem is that a result changes in the turn to search.
like a ['spun gold', 'gold', 'apple'] is ok,
but like a ['gold', 'spun gold', 'apple'] is ng.
If gold => <span class='hit'>gold</span> is performed first,
spun gold => <span class='hit'>spun gold</span> will go wrong.
(Since gold has changed to <span class='hit'>gold</span> by the 1st time.)
Is there better way?
EDIT:
As conditions, search is not only English.
I think I see the problem: one replacement is messing up a previous one because they share a common substring.
Perform a single replacement, by combining the terms in
relationinto one big “or” in the regexp:N.B. you may need to quote the array elements before
.join('|')ing them to prevent special characters from breaking the regexp. (Example:relation = ['foo', 'bar?']). Here’s how: Escape string for use in Javascript regex