Copy codeThe Code is as follows: // remove the leading space (left space) of the string)
Function LTrim (str ){
Var I;
For (I = 0; I <str. length; I ++ ){
If (str. charAt (I )! = "") Break;
}
Str = str. substring (I, str. length );
Return str;
}
// Remove the trailing space (right space) of the string)
Function RTrim (str ){
Var I;
For (I = str. length-1; I> = 0; I --){
If (str. charAt (I )! = "") Break;
}
Str = str. substring (0, I + 1 );
Return str;
}
// Remove the leading and trailing spaces (left and right spaces) of the string)
Function Trim (str ){
Return LTrim (RTrim (str ));
}
Delete all functions in the string
Js: delete string space functionCopy codeThe Code is as follows: function Jtrim (str)
{
Var I = 0;
Var len = str. length;
If (str = "") return (str );
J = len-1;
Flagbegin = true;
Flagend = true;
While (flagbegin = true) & (I <len ))
{
If (str. charAt (I) = "")
{
I = I + 1;
Flagbegin = true;
}
Else
{
Flagbegin = false;
}
}
While (flagend = true) & (j> = 0 ))
{
If (str. charAt (j) = "")
{
J = J-1;
Flagend = true;
}
Else
{
Flagend = false;
}
}
If (I> j) return ("");
Trimstr = str. substring (I, j + 1 );
Return trimstr;
}
The above method does not use regular expressions. Below we will try it using regular expressions.
Regular Expression Replacement spaceCopy codeThe Code is as follows: // remove spaces in the string
String. prototype. Trim = function (){
Return this. replace (/(^ s *) | (s * $)/g ,"");
}
// Remove spaces on the left of the string
String. prototype. LTrim = function (){
Return this. replace (/(^ s *)/g ,"");
}
// Remove spaces on the right of the string
String. prototype. RTrim = function (){
Return this. replace (/(s * $)/g ,"");
}
Delete all spacesCopy codeCode: var s = "asd ddd bbb sss ";
Var reg =/s/g;
Var ss = s. replace (reg ,"");
Alert (ss );
Remove all spaces in the string (including intermediate spaces. Set the 2nd parameter to g)Copy codeThe Code is as follows: function Trim (str, is_global)
{
Var result;
Result = str. replace (/(^ s +) | (s + $)/g ,"");
If (is_global.toLowerCase () = "g ")
Result = result. replace (/s/g ,"");
Return result;
}