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 ,"");
}