Heim  >  Artikel  >  Web-Frontend  >  javascript 去字符串空格终极版(支持utf8)_javascript技巧

javascript 去字符串空格终极版(支持utf8)_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:41:44882Durchsuche

其实这个问题是:如果你的js本身是unicode编码,那么用正则表达式s就可以去掉所有空白,但是如果你js是utf-8编码,那么正则就不能处理编码为160的空格了。

下面我先是正则表达式去掉编码为32的空格,再用递归的方法去掉字符串两边的unicode空格。

复制代码 代码如下:

/** 去字符两端空格 开始
*@author 敖士伟
*@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;
}
}

//--去字符两端空格 结束

//e.g.
var a = "  a  ";
alert("b" + a.trim() + "b");
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn