Skip to content

Instantly share code, notes, and snippets.

@neekey
Created August 24, 2012 03:24
Show Gist options
  • Save neekey/3445116 to your computer and use it in GitHub Desktop.
Save neekey/3445116 to your computer and use it in GitHub Desktop.
对文本进行替换(关键词搜索),提供不区分大小写
/**
* 文本替换
* @param target 需要搜索的文本
* @param keywords 关键字
* @param decorator 对搜索到的关键词进行构造
* @param ifSensitive 大小写是否区分,默认不区分
* @return {*}
*/
function textReplace( target, keywords, decorator, ifSensitive ){
var lowerCaseKeywords = keywords.toLowerCase();
ifSensitive = ( ifSensitive === undefined ) ? false : ifSensitive;
return target.replace(
new RegExp( '(' + lowerCaseKeywords + ')', 'g' + ( ifSensitive === true ? '' : 'i' ) ),
decorator( '$1' )
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment