jQuery源码 — trim方法

本文介绍了jQuery中的trim方法实现原理,包括使用原生JavaScript的trim方法和自定义实现去除字符串前后空白字符的功能。针对不同浏览器环境提供了兼容性解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

trim方法定义在jQuery.prototype


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 ');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值