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.