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.

1
  • Would it be ok if you just reorder relation-array? Commented Dec 2, 2012 at 6:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the advice. I tried. The result of ['tress', 'enchantress'] is <span class="hit">enchantress</span>. I want to it become like <span class="hit">enchan<span class="hit">tress</span></span> as my image. Is it possible?
If a pre-code is executed after this your code, it will become as my image. Thank you. (but is there wastefulness?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.