javascript String 的扩展方法集合
javascript String 的扩展方法集合
发布时间:2016-12-30 来源:查字典编辑
摘要://获取字符数组String.prototype.ToCharArray=function(){returnthis.split("");}...

//获取字符数组

String.prototype.ToCharArray=function()

{

returnthis.split("");

}

//获取N个相同的字符串

String.prototype.Repeat=function(num)

{

vartmpArr=[];

for(vari=0;i<num;i++)tmpArr.push(this);

returntmpArr.join("");

}

//逆序

String.prototype.Reverse=function()

{

returnthis.split("").reverse().join("");

}

//测试是否是数字

String.prototype.IsNumeric=function()

{

vartmpFloat=parseFloat(this);

if(isNaN(tmpFloat))returnfalse;

vartmpLen=this.length-tmpFloat.toString().length;

returntmpFloat+"0".Repeat(tmpLen)==this;

}

//测试是否是整数

String.prototype.IsInt=function()

{

if(this=="NaN")returnfalse;

returnthis==parseInt(this).toString();

}

//合并多个空白为一个空白

String.prototype.resetBlank=function()

{

returnthis.replace(/s+/g,"");

}

//除去左边空白

String.prototype.LTrim=function()

{

returnthis.replace(/^s+/g,"");

}

//除去右边空白

String.prototype.RTrim=function()

{

returnthis.replace(/s+$/g,"");

}

//除去两边空白

String.prototype.trim=function()

{

returnthis.replace(/(^s+)|(s+$)/g,"");

}

//保留数字

String.prototype.getNum=function()

{

returnthis.replace(/[^d]/g,"");

}

//保留字母

String.prototype.getEn=function()

{

returnthis.replace(/[^A-Za-z]/g,"");

}

//保留中文

String.prototype.getCn=function()

{

returnthis.replace(/[^u4e00-u9fa5uf900-ufa2d]/g,"");

}

//得到字节长度

String.prototype.getRealLength=function()

{

returnthis.replace(/[^x00-xff]/g,"--").length;

}

//从左截取指定长度的字串

String.prototype.left=function(n)

{

returnthis.slice(0,n);

}

//从右截取指定长度的字串

String.prototype.right=function(n)

{

returnthis.slice(this.length-n);

}

//HTML编码

String.prototype.HTMLEncode=function()

{

varre=this;

varq1=[/x26/g,/x3C/g,/x3E/g,/x20/g];

varq2=["&","<",">",""];

for(vari=0;i<q1.length;i++)

re=re.replace(q1[i],q2[i]);

returnre;

}

//Unicode转化

String.prototype.ascW=function()

{

varstrText="";

for(vari=0;i<this.length;i++)strText+=""+this.charCodeAt(i)+";";

returnstrText;

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类