js截取中英文字符串、标点符号无乱码示例解读
时间:2021-07-16 10:41:42|栏目:JavaScript代码|点击: 次
复制代码 代码如下:
<script>
function subString(str, len, hasDot)
{
var newLength = 0;
var newStr = "";
var chineseRegex = /[^\x00-\xff]/g;
var singleChar = "";
var strLength = str.replace(chineseRegex,"**").length;
for(var i = 0;i < strLength;i++){
singleChar = str.charAt(i).toString();
if(singleChar.match(chineseRegex) != null){
newLength += 2;
}else{
newLength++;
}
if(newLength > len){
break;
}
newStr += singleChar;
}
if(hasDot && strLength > len){
newStr += "...";
}
return newStr;
}
alert(subString("js截取中英文字符串无乱码",10,true));
</script>
上一篇:Ajax,UTF-8还是GB2312 eval 还是execScript
栏 目:JavaScript代码
下一篇:JavaScript ES6的新特性使用新方法定义Class
本文地址:http://www.codeinn.net/misctech/157771.html