trim方法定义在jQuery.prototype
有原生方法,用原生的,没有的话自定义,下面说自定义的部分
分别匹配前、后空白符,至于为啥有\xA0这东西,因为在IE中,\s无法匹配全角空格?翻译没错吧?
我参照写一个通用的
var trim = String.prototype.trim,//在jQuery闭包最开始的地方定义的
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
······
······
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
}
有原生方法,用原生的,没有的话自定义,下面说自定义的部分
// IE doesn't match non-breaking spaces with \s
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
分别匹配前、后空白符,至于为啥有\xA0这东西,因为在IE中,\s无法匹配全角空格?翻译没错吧?
我参照写一个通用的
var trim = String.prototype.trim ? function( text ) {
if( !text ) {
return '';
} else {
return String.prototype.trim.call(text);
}
} :
function( text ) {
var trimLeft = /^[\s\xA0]+/,
trimRight = /[\s\xA0]+$/;
return function(text){
if( !text ) {
return '';
}else{
return text.toString().replace(trimLeft, '').replace(trimRight, '');
}
}
}()
trim(' abc ');