Skip to content

Instantly share code, notes, and snippets.

@hehongwei44
Last active May 5, 2017 06:51
Show Gist options
  • Save hehongwei44/be3027aeb48ab978a039 to your computer and use it in GitHub Desktop.
Save hehongwei44/be3027aeb48ab978a039 to your computer and use it in GitHub Desktop.
js高级截取字符串功能
/**
*
* @descrition: 对字符串进行截取,包括普通字符和中文字符
* @param : str ->待截取的字符串
* @param : len ->要截取的长度
*
* 比如cutstr('hello',2)->he... cutstr("您好呀",4)->您好...
* 优先选择后台进行字符串截取,后css截取,最后js截取
*/
var cutstr = function(str, len) {
var temp,
icount = 0,
patrn = /[^\x00-\xff]/g, //中文字符匹配
strre = "";
for (var k = 0; k < str.length; k++) {
if (icount < len ) {
temp = str.substr(k, 1);
if (temp.match(patrn) == null) {
icount = icount + 1;
} else {
icount = icount + 2;
}
strre += temp;
} else {
break
}
}
return strre + "...";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment