JavaScript customization methods to implement Trim (), Ltrim (), Rtrim () function _javascript skills

Source: Internet
Author: User
Tags rtrim
Removing the spaces at each end of the string is a very common method of string processing, and unfortunately JavaScript does not have these three methods, only we have customized:
Step 1th, add members to string
Copy Code code as follows:

String.prototype.Trim = function () {return Trim (this);}
String.prototype.LTrim = function () {return LTrim (this);}
String.prototype.RTrim = function () {return RTrim (this);}

The second step is to implement the method
Copy Code code as follows:

function LTrim (str)
{
var i;
for (i=0;i<str.length;i++)
{
if (Str.charat (i)!= "" &&str.charat (i)!= "") break;
}
Str=str.substring (i,str.length);
return str;
}
function RTrim (str)
{
var i;
for (i=str.length-1;i>=0;i--)
{
if (Str.charat (i)!= "" &&str.charat (i)!= "") break;
}
Str=str.substring (0,i+1);
return str;
}
function Trim (str)
{
Return LTrim (RTrim (str));
}

Of course, you can also use regular expressions so that the code is clearer and more efficient,
Copy Code code as follows:

String.prototype.Trim = function ()
{
return This.replace (/(^\s*) | \s*$)/g, "");
}
String.prototype.LTrim = function ()
{
return This.replace (/(^\s*)/g, "");
}
String.prototype.RTrim = function ()
{
return This.replace (/(\s*$)/g, "");
}
Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.