However, if jquery and other frameworks are not used in the project, JS itself does not have such a function. We have to write such a function by ourselves. The specific implementation of the function is as follows:
CopyCode The Code is as follows: // it can be called by the user.
Function trim (s ){
Return trimright (trimleft (s ));
}
// Remove the left blank
Function trimleft (s ){
If (S = NULL ){
Return "";
}
VaR whitespace = new string ("\ t \ n \ r ");
VaR STR = new string (s );
If (whitespace. indexof (Str. charat (0 ))! =-1 ){
VaR J = 0, I = Str. length;
While (j <I & whitespace. indexof (Str. charat (j ))! =-1 ){
J ++;
}
STR = Str. substring (J, I );
}
Return STR;
}
// Remove the white space on the right
Function trimright (s ){
If (S = NULL) Return "";
VaR whitespace = new string ("\ t \ n \ r ");
VaR STR = new string (s );
If (whitespace. indexof (Str. charat (Str. Length-1 ))! =-1 ){
VaR I = Str. Length-1;
While (I> = 0 & whitespace. indexof (Str. charat (I ))! =-1 ){
I --;
}
STR = Str. substring (0, I + 1 );
}
Return STR;
}
You only need to call the trim function.
The following is the implementation method using regular expressions: Copy code The Code is as follows: <script language = "JavaScript">
<! --
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 ,"");
}
// -->
</SCRIPT>
<Input type = "text" value = "Leading and trailing spaces" id = "space">
<Input type = "button" value = "Remove leading and trailing spaces" onclick = "javascript: document. getelementbyid ('space '). value = document. getelementbyid ('space '). value. trim (); document. getelementbyid ('space '). select (); ">
<Input type = "button" value = "leading space" onclick = "javascript: document. getelementbyid ('space '). value = document. getelementbyid ('space '). value. ltrim (); document. getelementbyid ('space '). select (); ">
<Input type = "button" value = "space after removal" onclick = "javascript: document. getelementbyid ('space '). value = document. getelementbyid ('space '). value. rtrim (); document. getelementbyid ('space '). select (); ">
<Input type = "button" value = "Restore" onclick = "javascript: Document. getelementbyid ('space'). value = 'spaces before and after ';">
The above code is replaced by spaces due to editor issues. Therefore, please add spaces for testing.