All browsers since IE9+ have trim()
method for strings.
(自IE9 +起,所有浏览器都具有trim()
方法来处理字符串。)
For those browsers who does not support trim()
, you can use this polyfill from MDN :
(对于不支持trim()
浏览器,可以使用MDN中的以下polyfill:)
if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
That said, if using jQuery
, $.trim(str)
is also available and handles undefined/null.
(也就是说,如果使用jQuery
,则$.trim(str)
也是可用的,并且可以处理未定义/空值。)
See this:
(看到这个:)
String.prototype.trim=function(){return this.replace(/^s+|s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^s+/,'');};
String.prototype.rtrim=function(){return this.replace(/s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|
)s+|s+(?:$|
))/g,'').replace(/s+/g,' ');};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…