Skip to content

Instantly share code, notes, and snippets.

@vivisidea
Created February 4, 2013 06:03
Show Gist options
  • Save vivisidea/4705245 to your computer and use it in GitHub Desktop.
Save vivisidea/4705245 to your computer and use it in GitHub Desktop.
a simple javascript function to hilight text without breaking html tag, for example: hilight 'google' in '<a href="google.com">google</a>' --> '<a href="google.com"><span class="hilight">google</span></a>'
/** 带有html文本的关键词高亮 */
var hilight = function(input, word){
var splits = split(input);
for(i = 0; i<splits.length; i++){
if(splits[i][0] === '<' && splits[i][splits[i].length-1] ==='>') continue;
splits[i] = splits[i].replace(new RegExp(word, 'gi'), '<span class="hilight">'+word+'</span>');
}
return splits.join('');
}
/** 切成html标签文本和非html标签文本 */
var split = function(input){
if(typeof input === 'undefined' || input == '') return [];
var pattern = /<.*?>/gi
var result = pattern.exec(input);
var ret = [];
var lastIndex = 0;
while(result != null){
// console.log(result.index+", "+pattern.lastIndex);
if(lastIndex < result.index){
ret.push(input.substring(lastIndex, result.index));
}
ret.push(result[0]);
lastIndex = pattern.lastIndex;
result = pattern.exec(input);
}
if(lastIndex < input.length){
ret.push(input.substring(lastIndex));
}
return ret;
}
// console.log(hilight('', 'google'));
// console.log(hilight('google', 'google'));
// console.log(hilight('<a href="google.com">搜索</a>', 'google'));
// console.log(hilight('google blablabla<a href="http://google.com"> google search</a>blablabla google', 'google'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment