Last active
August 29, 2015 14:02
-
-
Save joecliff/88fb0485df73e29039c8 to your computer and use it in GitHub Desktop.
js highlight words function, support chinese
This file contains 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
'use strict'; | |
function convertKeywordsToRegStr(keywords) { | |
return '(' + keywords.trim().replace(/[^\w\u4E00-\u9FA5]+/g, '|') + ')'; | |
} | |
function getHighlightFn(keywords, highlightClass) { | |
var regexpStr = convertKeywordsToRegStr(keywords); | |
if (regexpStr.length === 2) { | |
return function (sourceText) { | |
return sourceText; | |
}; | |
} | |
var regexp = new RegExp(regexpStr, 'ig'); | |
var replaceTo = '<span class="' + highlightClass + '">$1</span>'; | |
return function (sourceText) { | |
return sourceText.replace(regexp, replaceTo); | |
}; | |
} | |
var fn = getHighlightFn('测试 中国', 'hl'); | |
console.log(fn('abc'));//abc | |
console.log(fn('我要测试下'));//我要<span class="hl">测试</span>下 | |
console.log(fn('我要测试下,中国啊啊'));//我要<span class="hl">测试</span>下,<span class="hl">中国</span>啊啊 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment