0
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.

R.Atim
  • 367
  • 7
  • 16

1 Answers1

3

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 relation into one big "or" in the regexp:

var target   = $('.target-text'),
    relation = ['spun gold', 'gold', 'apple'],
    re = new RegExp(relation.join('|'), 'ig');

target.html(function (_, oldHtml) {
    return oldHtml.replace(re, "<span class='hit'>$&</span>");
});

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

Community
  • 1
  • 1
Matt Ball
  • 332,322
  • 92
  • 617
  • 683
  • Thank you for the advice. I tried. The result of `['tress', 'enchantress']` is `enchantress`. I want to it become like `enchantress` as my image. Is it possible? – R.Atim Dec 02 '12 at 07:08
  • If a pre-code is executed after this your code, it will become as my image. Thank you. (but is there wastefulness?) – R.Atim Dec 02 '12 at 07:29