现在的位置: 首页 > 综合 > 正文

jQuery源码分析7: jQuery.trim

2019年10月30日 ⁄ 综合 ⁄ 共 766字 ⁄ 字号 评论关闭

jQuery源码分析7: jQuery.trim

// Used for trimming whitespace
var trimLeft = /^\s+/,
    trimRight = /\s+$/,
    trim = String.prototype.trim;  //< JavaScript直到1.8.1才支持trim

// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,

//< 在ie中不换行符号non-break('\xA0')不算作空白,即不在字符集[\s]中,但在其他浏览器则属于空白,所以在jQuery中针对ie作了加强处理
if ( rnotwhite.test( "\xA0" ) ) {
    trimLeft = /^[\s\xA0]+/;
    trimRight = /[\s\xA0]+$/;
}

// < 若支持原生的String.prototype.tim则直接使用其过滤字符串两侧的空白,否则使用replace过滤两侧的空白
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, "" );

    },

补充

最后需要提到的是ECMA-262(V5)中为String提供原生的trim方法.此外Molliza Gecko 1.9.1引擎中还给String添加了trimLeft,trimRight方法.

抱歉!评论已关闭.