JavaScript custom methods implement trim (), Ltrim (), Rtrim () Functions

Source: Internet
Author: User
Tags rtrim

Removing spaces at both ends of a string is a very common method for string processing. Unfortunately, JavaScript does not have these three methods, which are only customized:
Step 2: Add a member to String
Copy codeThe Code is as follows:
String. prototype. Trim = function () {return Trim (this );}
String. prototype. LTrim = function () {return LTrim (this );}
String. prototype. RTrim = function () {return RTrim (this );}

Step 2: Implementation Method
Copy codeThe Code is 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 to make the code clearer and more efficient,
Copy codeThe Code is 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.