If we write in the project that when the user enters spaces during registration, how do we remove the spaces?
The following is the js I often use to share with you:
The first type: Loop check and replace
[javascript]
//For users to call
function trim(s){
return trimRight(trimLeft(s));
}
//Remove the left blank
function trimLeft( s){
if(s == null) {
return "";
}
var whitespace = new String(" tnr");
var str = new String(s) ;
if (whitespace.indexOf(str.charAt(0)) != -1) {
var j=0, i = str.length;
while (j < i && whitespace.indexOf (str.charAt(j)) != -1){
j ;
}
str = str.substring(j, i);
}
return str;
}
//Remove the whitespace on the right www.jb51.net
function trimRight(s){
if(s == null) return "";
var whitespace = new String(" tnr" );
var str = new String(s);
if (whitespace.indexOf(str.charAt(str.length-1)) != -1){
var i = str.length - 1;
while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){
i--;
}
str = str.substring( 0, i 1);
}
return str;
}
Second: regular replacement [javascript]
Third method: use jquery [javascript]
$.trim(str)
The internal implementation of jquery is:
[javascript]
function trim(str){
return str.replace(/^(s|u00A0) / ,'').replace(/(s|u00A0) $/,'');
}
The fourth way: use motorcycles [javascript ]
function trim(str){
return str .replace(/^(s|xA0) |(s|xA0) $/g, '');
}
The fifth way: cutting strings [javascript]
function trim(str) {
str = str.replace(/^(s|u00A0) /,'');
for(var i=str.length-1; i>=0; i--){
if(/S/.test(str.charAt(i))){
str = str.substring(0, i 1);
break;
}
}
return str ;
}
After testing, the fifth method is the most efficient when processing long strings.
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31