使用自带接口 trim(),考虑兼容性:
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+/, "").replace(/\s+$/,"");
}
}
// test the function
var str = " \t\n test string ".trim();
alert(str == "test string"); // alerts "true"
这段代码实现了一个JavaScript函数,用于在String对象上添加trim()方法,如果原生不支持的话。这个函数使用正则表达式去除字符串首尾的空白字符,确保了在各种环境中都能正确处理teststring这样的例子。
使用自带接口 trim(),考虑兼容性:
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+/, "").replace(/\s+$/,"");
}
}
// test the function
var str = " \t\n test string ".trim();
alert(str == "test string"); // alerts "true"

被折叠的 条评论
为什么被折叠?
&spm=1001.2101.3001.5002&articleId=128754845&d=1&t=3&u=862cf386feef4aa08de02c4fe5af1754)