Home > Web Front-end > JS Tutorial > body text

5 implementation methods and comparisons of js removing spaces before and after strings_javascript skills

WBOY
Release: 2016-05-16 17:38:24
Original
1199 people have browsed it

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]

Copy code The code is as follows:

//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]
Copy code The code is as follows:



Third method: use jquery
[javascript]
Copy code The code is as follows:

$.trim(str)

The internal implementation of jquery is:
[javascript]
Copy code The code is as follows:

function trim(str){
return str.replace(/^(s|u00A0) / ,'').replace(/(s|u00A0) $/,'');
}

The fourth way: use motorcycles
[javascript ]
Copy code The code is as follows:

function trim(str){
return str .replace(/^(s|xA0) |(s|xA0) $/g, '');
}

The fifth way: cutting strings
[javascript]
Copy code The code is as follows:

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.
Copy code The code is as follows:

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!