We often encounter this situation when the front-end interacts with the background staff. We often need to obtain the user input information in the text box, and then submit it to the background through ajax or form. However, when a user inputs information, there is no space at both ends of the user input data. Of course, these spaces are meaningless in general, so we need to eliminate the spaces at both ends of the data before transmitting the data to the background. To ensure universality, spaces at the left, right, and left and right ends are cleared.
1. Remove spaces on the left of the string
Copy codeThe Code is as follows:
Function leftTrim (str ){
Return str. replace (/^ \ s */, ""); // ^ indicates matching from the beginning to the left
}
// Alert ("111" + leftTrim ("aaa") + "111"); // use 111 on both sides as a reference to determine whether spaces are deleted
2. Remove spaces on the right of the string
Copy codeThe Code is as follows:
Function rightTrim (str ){
Return str. replace (/\ s * $ /,"");
}
// Alert ("111" + rightTrim ("aaa") + "111"); // use 111 on both sides as a reference to determine whether spaces are deleted
3. Remove spaces on both sides of the string
Copy codeThe Code is as follows:
Function trim (str ){
Return str. replace (/(^ \ s *) | (\ s * $)/g ,"");
}
// Alert ("111" + trim ("aaa") + "111"); // use 111 on both sides as a reference to determine whether spaces are deleted
Of course, for convenience, we can also expand functions in strings
Copy codeThe Code is as follows:
String. prototype. trim = function (){
Return trim (this );
}
Var str = "aaa ";
Alert ("111" + str. trim () + "111"); // use 111 on both sides as a reference to determine whether spaces are deleted.
PS: if you are using jquery, you can ignore the above, simply use the tool function $. trim.