JavaScript go to string Space Ultimate version (support UTF8) _javascript tips

Source: Internet
Author: User
In fact, the problem is: If your JS itself is Unicode encoding, then use the regular expression \s can remove all the blanks, but if you JS is utf-8 encoding, then you can not process the encoding of 160 of the space.

I'll take a regular expression to remove the space encoded in 32, and then use the recursive method to remove the Unicode spaces on either side of the string.
Copy Code code as follows:

/** go to character two-space start
* @author Oswei
* @version v1.0
* @date 2009/11/14 22:51
/
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)
Retu RN "";
if (s.charcodeat (s.length-1) = = 160) {
S = s.substr (0, s.length-1);
return Rremoveblank (s);
}
Else {
return s;
}
}

//--the end of a character with a space ending

//e.g.
var a = "  a  ";
Alert ("B" + A.trim () + "B");

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.