Usually, when the form is validated, the text of the input box needs to be taken out of the string and trailing blanks.
The current version of the browser is natively supported by the trim () method, and the previous version of JQ also implements support for the method.
Boring time can be concerned about how to achieve, sometimes written interview will also ask, by the way review the regular.
Remove the end and end spaces + use regular, nothing more than to find the match to the white space character, and then put it/they replace it. Understand the sermon, but there are all roads through Rome.
1. Regular method: Match the first and the trailing blanks separately, then remove
1 function Trim (str) {2 return str.replace (/^\s\s*/, "). Replace (/\s\s*$/,"); 3 }
Version 2.JQ: This regular method of the object is the global str, relative to the first, a little slower, but look good
1 function Trim (str) {2 return str.replace (/^\s+|\s+$/g, "); 3 }
3. Ultimate version: Return to the original idea, just use the regular to remove the first space, find the trailing space, use substring to intercept it, avoid using regular to find a global replacement, improve performance
1 functionTrim (str) {2 varstr = str.replace (/^\s+/, "), I = 0, L =str.length;3 for(; i<len,i++){4 if(/\s/. Test (Str.charat (i))) {5str = str.substring (0, i+1);//or str.substr (0, i);6 Break;7 }8 }9 returnstr;Ten}
Reference book: JavaScript Framework Design-Masaki
JS Trim () Remove string and trailing blanks