Regular delete string left, right or both ends of the space experience Summary _ regular expression

Source: Internet
Author: User

When we are interacting with the backend people, we often encounter situations where we often need to get the information that the user enters in the text box and then submit it to the background via Ajax or form. However, when the user enters the information, we cannot guarantee that the data entered by the user has no spaces at both ends. Of course, these spaces are generally meaningless, so it is necessary to eliminate the spaces on both ends of the data before transferring it to the background. In order to ensure versatility, for the left, right and both sides of the space clearance, the following are enumerated.

1. Eliminate the space on the left side of the string

Copy Code code as follows:

function Lefttrim (str) {
Return Str.replace (/^\s*/, "");//^ symbol indicates matching from the beginning to the left
}
Alert ("A" +lefttrim ("AAA") + "111"), or 111 on both sides as a reference to determine whether the space is deleted

2. Eliminate the space on the right side of the string
Copy Code code as follows:

function Righttrim (str) {
Return Str.replace (/\s*$/, "");
}
Alert ("A" +righttrim ("AAA") + "111"), or 111 on both sides as a reference to determine whether the space is deleted

3. Eliminate space on both sides of the string
Copy Code code as follows:

function Trim (str) {
Return Str.replace (/(^\s*) | ( \s*$)/g, "");
}
Alert ("A" +trim ("AAA") + "111"), or 111 on both sides as a reference to determine whether the space is deleted

Of course, in order to facilitate, we can also expand the function in the string
Copy Code code as follows:

String.prototype.trim = function () {
Return trim (this);
}
var str = "AAA";
Alert ("+str.trim" () + "111"), or 111 on both sides as a reference to determine whether the space is deleted

PS: If you are using jquery, the above can be ignored, directly using the tool function $.trim () can be.

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.