Home  >  Article  >  Web Front-end  >  js prototype截取字符串函数_javascript技巧

js prototype截取字符串函数_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:30:53836browse

prototype它是用Javascript写好的一些API,包括对Javascript中的类如String,Array等进行的扩充,把JS文件嵌入后直接用就行了.

复制代码 代码如下:

String.prototype.strLen = function() {
var len = 0;
for (var i = 0; i if (this.charCodeAt(i) > 255 || this.charCodeAt(i) }
return len;
}
//将字符串拆成字符,并存到数组中
String.prototype.strToChars = function(){
var chars = new Array();
for (var i = 0; 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) 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 if(this.charsArray[i][1])
len += 2;
else
len++;
if (end return str;
else if (start str += this.charsArray[i][0];
}
return str;
}
//截取字符串(从start字节截取length个字节)
String.prototype.subCHStr = function(start, length){
return this.subCHString(start, start + length);
}
var li= document.getElementsByName("listtitle");
for(var i=0;i{
li[i].innerHTML=li[i].innerHTML.subCHStr(0,28)+"...";
}

prototype是用于对原型对象的继承,主要是为了节省内存空间。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn