Last active
May 5, 2017 06:51
-
-
Save hehongwei44/be3027aeb48ab978a039 to your computer and use it in GitHub Desktop.
js高级截取字符串功能
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
/** | |
* | |
* @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