js 字符串(中文)获取长度 截取中文字符串
<script type="text/javascript" >
/*
*自定义字符串属性
*/
//计算字符串长度
String.prototype.strLen = function() {
var len = 0;
for (var i = 0; i < this.length; i++) {
if (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0) len += 2; else len ++;
}
return len;
}
//将字符串拆成字符,并存到数组中
String.prototype.strToChars = function(){
var chars = new Array();
for (var i = 0; i < this.length; i++){
chars[i] = [this.substr(i, 1), this.isCHS(i)];
}
String.prototype.charsArray = chars;
return chars;
}
//判断某个字符是否是汉字
String.prototype.isCHS = function(i){
if (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0)
return true;
else
return false;
}
//截取字符串(从start字节到end字节)
String.prototype.subCHString = function(start, end){
var len = 0;
var str = "";
this.strToChars();
for (var i = 0; i < this.length; i++) {
if(this.charsArray[i][1])
len += 2;
else
len++;
if (end < len)
return str;
else if (start < len)
str += this.charsArray[i][0];
}
return str;
}
//截取字符串(从start字节截取length个字节)
String.prototype.subCHStr = function(start, length){
return this.subCHString(start, start + length);
}
//运行实例
var str1 = str.subCHStr(20,0);
var str2 = str.subCHString(20,40);
alert(str1 + " == " + str2);
</script>
<script type="text/javascript" >
//附带一个单独计算长度函数
var str_len = getLen(str);
// alert(str_len);
function getLen( str) {
var totallength=0;
for (var i=0;i<str.length;i++)
{
//charCodeAt 返回一个整数,获得字符的unicode编码
var intCode=str.charCodeAt(i);
if (intCode>=0&&intCode<=128) {//为字符的编码范围
totallength=totallength+1;//非中文单个字符长度加1
}
else {
totallength=totallength+2;//中文字符长度则加2
}
}
return totallength;
}
</script>
文章来自:http://www.3lian.com/edu/2014/03-19/135471.html