jQuery.trim( str )

来源:互联网 发布:网络吃饼干是什么意思 编辑:程序博客网 时间:2024/09/21 09:21

2.8.7 jQuery.trim( str )

方法jQuery.trim( str ) 用于移除字符串开头和结尾的空白符。如果传入的参数是 null 或
undefined,则返回空字符串;如果传入的参数是对象,则先获取对象的字符串表示,然后移
除开头和结尾的空白符,并返回。相关代码如下所示:

 43     //  Check if a string has a non-whitespace character in it 44     rnotwhite = /\S/,  45 46      //  Used for trimming whitespace 47     trimLeft = /^\s+/, 48     trimRight = /\s+$/, 91     trim = String.prototype.trim,910  //  IE doesn't match non-breaking spaces with \s911  if ( rnotwhite.test( "\xA0" ) ) {912     trimLeft = /^[\s\xA0]+/;913     trimRight = /[\s\xA0]+$/;914  }668      //  Use native String.trim function wherever possible669     trim: trim ?670         function( text ) {671             return text == null ?672                 "" :673                 trim.call( text );674         } :675 676         //  Otherwise use our own trimming functionality677         function( text ) {678             return text == null ?679                 "" :680                 text.toString().replace( trimLeft, "" ).replace( trimRight, "" );681         },

第47~4 8 行:正则trimLeft 用于匹配字符串开头的空白符;trimRight 用于匹配字符串结尾的空白符。
第911 ~914 行:在IE 9 以下的浏览器中,\s 不匹配不间断空格\xA0,需要为正则 trimLeft 和trimRight 加上“\xA0”。
第669 ~681 行:如果浏览器支持 String.prototype.trim() 则“借鸡生蛋”,String.prototype.trim() 是ECMAScript 5新增的String 原型方法;如果不支持,则先调用方法toString() 得到参数text 的字符串表示,然后调用方法replace() 把正则trimLeft 和trimRight 匹配到的空白符替换为空字符串。如果参数是null 或undefined,则返回空字符串。

0 0
原创粉丝点击