replace() word-border g.
, . , , , JS. , :)
var WordsToMatch = new Array('fox', 'dog');
var MaxHighlights = 2;
var TestStr =
'The quick brown fox jumps over the lazy dog but the lazy dog is '+
'quick of the mark to catch the brown fox. In general the ' +
'fox versus the dog is not a good match.';
document.write(highlight(TestStr, WordsToMatch, MaxHighlights));
function highlight (str, words, limit)
{
for(var i = 0; i < words.length; i++)
{
var pattern = new RegExp("\\b" + words[i] + "\\b","gi");
var j = 0;
str = str.replace(pattern, function (w) {
j++; return ((limit <= 0) || (j <= limit)) ? "<b>" + w + "</b>" : w;
});
}
return str;
}
, .
:
, , . , .
: , ...
.
, , , . , : ? , split-sequence (var sep_punct), , .
var WordsToMatch = new Array('fox', 'dog');
var TestStr =
'The quick brown fox jumps over the lazy dog but the lazy dog is '+
'quick of the mark to catch the brown fox. In general the ' +
'fox versus the dog is not a good match.';
function higlight_first_w_in_sentence(str, words)
{
var sep_punct = '[.;?!]';
var pattern = new RegExp(sep_punct + "\\s+(?=[A-Z0-9])", "g");
var sep = str.match(pattern);
var snt = str.split(pattern);
if((typeof snt != 'undefined') && (Object.prototype.toString.call(snt) === '[object Array]'))
{
for(var i = 0; i < snt.length; i++)
{
for(var j = 0; j < words.length; j++)
{
var pattern = new RegExp("\\b" + words[j] + "\\b", "i");
snt[i] = snt[i].replace(pattern, "<b>$&</b>");
}
}
if((typeof sep != 'undefined') && (Object.prototype.toString.call(sep) === '[object Array]') && (sep.length > 0) &&
(typeof snt != 'undefined') && (Object.prototype.toString.call(snt) === '[object Array]') && (snt.length > sep.length)
)
{
var ret = "";
for(var j = 0; j < snt.length; j++)
{
if(j>0) {
ret += (typeof sep[j-1] != 'undefined') ? sep[j-1] : " ";
}
ret += snt[j];
}
return ret;
}
return snt.join(" ");
}
return str;
}
document.write(higlight_first_w_in_sentence(TestStr, WordsToMatch));
:
, . .