您的位置:首页 > 其它

正则表达式 删除string首尾的空白

2012-06-26 13:52 197 查看
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+/, "").replace(/\s+$/, "");
};
}

var str = " \t\n test string ".trim();
console.log(str == "test string");//true


混合解决方案:用正则表达式方法过滤头部空白,用非正则表达式的方法过滤尾部字符。

String.prototype.trim = function() {
var str = this.replace(/^\s+/, ""),
end = str.length - 1,
ws = /\s/;

while (ws.test(str.charAt(end))) {
end--;
}

return str.slice(0, end + 1);
};


删除字符串内所有空格

//删除String中的所有空格
String.prototype.trim = function () {
return this.replace(/\s+/g, "");
};


trim性能比拼:http://rubylouvre.github.com/labs/trim_performance
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: