So I have written this code here:
highlighter: function (item) {
var parts = this.query.split(" ");
var length = parts.length;
for (var i = 0; i < length; i++){
if(parts[i] != ""){
item = item.replace(new RegExp('(' + parts[i] + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
})
}
}
return item;
}
What it does is:
- I have the string
item, and the stringthis.query - I split
this.queryat each space, and put the resulting substrings intoparts[]
My goal is to make every occurrence of a substring from parts[] in item bold.
So if
item = "This is some text"
and
this.query = "This some"
I want <strong>This</strong> is <strong>some</strong> text.
This works perfectly, except when I get matches in the <strong> element itself. So I want only the matches replaced that aren’t in the strong tag itself. Because I get resulting strings with ong> or trong>in it. Is this possible?
If you want to avoid the strong tags, do the replacement all in one step:
You’ll still have a problem if "item" contains strong before you begin, but otherwise you won’t have a problem.
Edit:
Let’s say you want to match "this", "that" and, "the other". A regular expression, or
RegExpfor that isThis|some|the other. Oddly enough, the string passed tonew RegExpis parsed as a regular exrpession.The other important thing to note is that
item.replace(regex, callback)will replace every match it finds with the result of callingcallback(match, ...)for each one. The first argument passed to callback is the entire match of the regex, while the remaining arguments are the groups within the match.If you want to know more, read up on regular expressions.