Escape string space using javascript (utf8 supported)

Source: Internet
Author: User

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 ");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.