Created
December 3, 2012 14:38
-
-
Save meglio/4195394 to your computer and use it in GitHub Desktop.
highligh(string, [words]) JS function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns { highlighted: ..., count: ... } | |
function highlight(str, words) | |
{ | |
var before = '<strong class="highlight">', beforeLen = before.length, | |
after = '</strong>', afterLen = after.length | |
if (typeof words == "string") | |
words = [words] | |
if (words == null || words.length == 0) | |
return { highlighted: str, count: 0 } | |
var count = 0 | |
$.each(words, function(i, w){ | |
w = $.trim(w).toLowerCase() | |
if (w == '') | |
return | |
var lower = str.toLowerCase(), lowerLen = lower.length, | |
wLen = w.length, offset = 0, searchStart = 0 | |
while(true) | |
{ | |
if (searchStart > lowerLen-1) | |
break | |
var pos = lower.indexOf(w, searchStart) | |
if (pos == -1) | |
break | |
searchStart = pos + 1 | |
pos += offset // found position with offset after previous replacements | |
str = str.slice(0, pos) + before | |
+ str.slice(pos, pos+wLen) + after | |
+ str.slice(pos+wLen) | |
offset += beforeLen + afterLen | |
count++ | |
} | |
}) | |
return { highlighted: str, count: count } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment