Skip to content

Instantly share code, notes, and snippets.

@meglio
Created September 13, 2012 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meglio/3716545 to your computer and use it in GitHub Desktop.
Save meglio/3716545 to your computer and use it in GitHub Desktop.
Function to highlight one or more words in a string
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 str
$.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
}
})
return str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment