A JavaScript String extension method collection _javascript Tips
Source: Internet
Author: User
Get an array of characters
String.prototype.tochararray=function ()
{
Return This.split ("");
}
Get n the same string
String.prototype.repeat=function (num)
{
var tmparr=[];
for (Var i=0;i<num;i++) Tmparr.push (this);
Return Tmparr.join ("");
}
Reverse
String.prototype.reverse=function ()
{
Return This.split (""). Reverse (). Join ("");
}
Test whether it is a number
String.prototype.isnumeric=function ()
{
var tmpfloat=parsefloat (this);
if (isNaN (Tmpfloat)) return false;
var tmplen=this.length-tmpfloat.tostring (). length;
return tmpfloat+ "0". Repeat (Tmplen) ==this;
}
Test whether it is an integer
String.prototype.isint=function ()
{
if (this== "NaN") return false;
Return This==parseint (This). ToString ();
}
Merge multiple blanks into one blank
String.prototype.resetBlank = function ()
{
Return This.replace (/s+/g, "");
}
Remove left blank
String.prototype.LTrim = function ()
{
Return This.replace (/^s+/g, "");
}
Remove Right blank
String.prototype.RTrim = function ()
{
Return This.replace (/s+$/g, "");
}
Remove both sides of white space
String.prototype.trim = function ()
{
Return This.replace (/(^s+) | ( s+$)/g, "");
}
Keep numbers
String.prototype.getNum = function ()
{
Return This.replace (/[^d]/g, "");
}
Keep Letters
String.prototype.getEn = function ()
{
Return This.replace (/[^a-za-z]/g, "");
}
Keep Chinese
String.prototype.getCn = function ()
{
Return This.replace (/[^u4e00-u9fa5uf900-ufa2d]/g, "");
}
Get byte length
String.prototype.getRealLength = function ()
{
Return This.replace (/[^x00-xff]/g, "--"). Length;
}
To intercept a string of a specified length from the left
String.prototype.left = function (n)
{
Return This.slice (0,n);
}
To intercept a string of a specified length from the right
String.prototype.right = function (n)
{
Return This.slice (THIS.LENGTH-N);
}
HTML encoding
String.prototype.HTMLEncode = function ()
{
var re = this;
var q1 = [/x26/g,/x3c/g,/x3e/g,/x20/g];
var q2 = ["&", "<", ">", ""];
for (Var i=0;i<q1.length;i++)
Re = Re.replace (Q1[i],q2[i]);
return re;
}
Unicode conversion
String.prototype.ascW = function ()
{
var strText = "";
for (var i=0; i<this.length; i++) StrText + = "&#" + this.charcodeat (i) + ";";
return strText;
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.