$.trim是怎么实现的

73 阅读1分钟

首先来看看zepto是怎么实现的

$.trim = function(str) {
    return str == null ? "" : String.prototype.trim.call(str)
  }

它调用了字符串的trim方法来处理【ES5增加的方法】 在jQuery 1.2.6中

trim: function( text ) {
		return (text || "").replace( /^\s+|\s+$/g, "" );
	},

使用了正则表达式去掉前后空格 在jQuery1.6.1中

trim = String.prototype.trim,
trim: trim ?
		function( text ) {
			return text == null ?
				"" :
				trim.call( text );
		} :
	//trimLeft = /^\s+/,
	  // trimRight = /\s+$/,
		function( text ) {
			return text == null ?
				"" :
				text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
		},

检查浏览器支持trim方法不,支持就调用浏览器本身的,不支持就用正则 在jQuery1.7中trim方法和jQuery1.6.1中一致 在jQuery2.0.3中很有意思

core_version = "2.0.3",
core_trim = core_version.trim,
 trim: function(text) {
            return text == null ? "" : core_trim.call(text);
        },

它借用了core_version这个字符串的trim方法 在JQuery2.1.1中又使用了正则

rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Support: Android<4.1
		trim: function(text) {
			return text == null ?
				"" :
				(text + "").replace(rtrim, "");
		},

它说是为了支持Android<4.1,所以用了正则