Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
js highlight words function, support chinese
'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