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:
Copy codeThe Code is as follows:
// For the user to call
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 codeThe 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.