Experience in deleting spaces on the left, right, or both ends of a string using regular expressions

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.