Home > Web Front-end > JS Tutorial > javascript string space removal ultimate version (supports utf8)_javascript skills

javascript string space removal ultimate version (supports utf8)_javascript skills

WBOY
Release: 2016-05-16 18:41:44
Original
927 people have browsed it

In fact, the problem is: if your js itself is unicode encoded, then you can use regular expression s to remove all white spaces, but if your js is utf-8 encoded, then the regular expression cannot handle spaces encoded as 160.

Below I first use a regular expression to remove the spaces coded as 32, and then use a recursive method to remove the unicode spaces on both sides of the string.

Copy code The code is as follows:

/**Remove spaces from both ends of characters Start
*@author Ao Shiwei
*@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)
return "";
if (s.charCodeAt(s.length-1) == 160) {
s = s.substr(0, s.length - 1);
return Rremoveblank(s);
}
else {
return s;
}
}

//-Remove both ends of characters Ending with spaces

//e.g.
var a = " a ";
alert("b" a.trim() "b");
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template