Skip to content

Commit 1c0a99c

Browse files
committed
Replace all words at one time by joining all words as one regexp.
2 parents 57e80a9 + a020951 commit 1c0a99c

File tree

1 file changed

+27
-27
lines changed

1 file changed

+27
-27
lines changed

jquery.highlighttextarea.js

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -87,40 +87,40 @@
8787

8888
var matches = [];
8989

90-
var wordColorMap = {};
90+
var wordColorMap = {},
91+
allWords = [];
9192
$.each(this.settings.words, function (color, words) {
9293
$.each(words, function (index, word) {
9394
wordColorMap[word] = color;
95+
allWords.push(word);
9496
});
9597
});
9698

97-
$.each(wordColorMap, function (word, color) {
99+
var allWordsRe = allWords.map(function (word) {
98100
var wordsRe = htmlDecode(word);
99-
var re = that.spacer + '(' + wordsRe + ')' + that.spacer;
100-
var regex = new RegExp(re, that.regParam);
101-
102-
var wordMatches = text.match(regex);
103-
if (wordMatches) {
104-
word = htmlDecode(word);
105-
matches.push(word);
106-
text = text.replace(
107-
new RegExp(that.spacer + word + that.spacer, that.regParam),
108-
function(innerMatch, start, contents) {
109-
var encodedMatch = innerMatch
110-
.replace(/[&"<>]/g, function (c) {
111-
return {
112-
'&': "&amp;",
113-
'"': "&quot;",
114-
'<': "&lt;",
115-
'>': "&gt;"
116-
}[c];
117-
});
118-
119-
return '<mark style="background-color:'+ color +';">' + encodedMatch + '</mark>';
120-
}
121-
);
122-
}
123-
});
101+
var re = '(' + that.spacer + wordsRe + that.spacer + ')';
102+
return re;
103+
}).join('|');
104+
var regex = new RegExp(allWordsRe, that.regParam);
105+
106+
var wordMatches = text.match(regex);
107+
if (wordMatches) {
108+
text = text.replace(regex, function(innerMatch, start, contents) {
109+
matches.push(innerMatch);
110+
var encodedMatch = innerMatch
111+
.replace(/[&"<>]/g, function (c) {
112+
return {
113+
'&': "&amp;",
114+
'"': "&quot;",
115+
'<': "&lt;",
116+
'>': "&gt;"
117+
}[c];
118+
});
119+
120+
var color = wordColorMap[innerMatch];
121+
return '<mark style="background-color:'+ color +';">' + encodedMatch + '</mark>';
122+
});
123+
}
124124

125125
$.each(this.settings.ranges, function(i, range) {
126126
if (range.start < text.length) {

0 commit comments

Comments
 (0)