In fact, this problem is: If your js itself is unicode encoding, you can use the regular expression \ s to remove all spaces, but if your js is UTF-8 encoding, therefore, regular expressions cannot process spaces encoded as 160.
Below I first remove the 32-encoded space from the regular expression, and then use recursive methods to remove the unicode spaces on both sides of the string.
Copy codeThe Code is as follows:
/** Start with a space at both ends
* @ Author Shi Wei
* @ Version v1.0
* @ Date 2009/11/14
*/
String. prototype. trim = function (){
Var r = this. replace (/(^ \ s *) | (\ s * $)/g ,"");
R = Lremoveblank (r );
R = Rremoveblank (r );
Return r;
}
Function Lremoveblank (s ){
If (s. length = 1 & s. charCodeAt (0) = 160)
Return "";
If (s. charCodeAt (0) = 160 ){
S = s. substr (1, s. length-1 );
Return removeblank (s );
}
Else {
Return s;
}
}
Function Rremoveblank (s ){
If (s. length = 1 & s. charCodeAt (0) = 160)
Return "";
If (s. charCodeAt (s. length-1) = 160 ){
S = s. substr (0, s. length-1 );
Return Rremoveblank (s );
}
Else {
Return s;
}
}
// -- End with space at both ends of the deprecated character
// E.g.
Var a = "";
Alert ("B" + a. trim () + "B ");