代码之家  ›  专栏  ›  技术社区  ›  jAndy

jQuerys$.trim(),bug还是写得不好?

  •  9
  • jAndy  · 技术社区  · 14 年前

    $.trim()

    /^(\s|\u00A0)+|(\s|\u00A0)+$/g
    

    var mystr = '    some test --          more text            new test                                         xxx';
    mystr = mystr.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, "");
    

    此代码 Firefox和Chrome,只需要一辈子。” mystr hex 160(A0) 角色。这个“问题”只有在没有预设的情况下才会发生 whitespace/A0

    此表达式:

    /^[\n\r\t \xA0]+|[\n\r\t \xA0]$/g
    

    在所有测试场景中都可以正常工作。也许有更好的模式?

    http://code.jquery.com/jquery-1.4.2.js

    更新

    A0 字符被替换。 Firebug console 也将替换粘贴时的字符,您必须在seperate html文件/编辑器中创建自己的字符串来测试这一点。

    3 回复  |  直到 14 年前
        1
  •  9
  •   Nick Craver    14 年前

    这是一个 known bug ,正如评论中所说,新月是正确的,它的这种方式 1.4.2 ,但已在下一版本中修复。

    你可以测试 String.prototype.trim http://jsfiddle.net/dLLVN/
    我在Firefox中的Chrome 117ms中运行了大约79ms,运行了一百万次……所以这将解决悬而未决的问题:)

    至于修复, take a look at the current source that'll be in 1.4.3

    今年3月,共有2起犯罪:


    1.4.2 $.trim() function :

    trim: function( text ) {
        return (text || "").replace( rtrim, "" );
    },
    

    1.4.3 $.trim() function :

    //earlier: 
    trim = String.prototype.trim
    
    //new trim here
    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, "" );
      }
    

    trimLeft trimRight 不同,取决于你是否在IE中,如下所示:

    trimLeft = /^\s+/,
    trimRight = /\s+$/,
    
    // Verify that \s matches non-breaking spaces
    // (IE fails on this test)
    if ( !/\s/.test( "\xA0" ) ) {
      trimLeft = /^[\s\xA0]+/;
      trimRight = /[\s\xA0]+$/;
    }
    
        2
  •  7
  •   sth Wojciech Parzych    14 年前

    通常是这样的表达 ^\s+|\s+$ 应该足够修剪了,因为 \s 应该匹配所有空格字符,甚至 \0xa0 不间断空格 1 . 此表达式应在不引起任何问题的情况下运行。

    现在可能jQuery想要支持的某些浏览器不匹配 具有 \s码 为了解决这个问题,jQuery添加了另一种方法 (\s|\0xa0) ,以修剪掉浏览器上不间断的空格。

    (\s|\0xa0)+$ ,这会导致浏览器出现问题 \0xa0型 \s码 . 在包含一长串 \0xa0型 \0xa0型 \0xa0型 字符不在字符串末尾,尾随 $ 条件永远不可能被满足,无论哪个空间被匹配 \s码 与之匹配的 \0xax ,但浏览器不知道这一点,会尝试所有组合,可能会搜索很长时间。

    你所建议的简化表达是不够的,因为 应该匹配所有unicode空格字符,而不仅仅是众所周知的ASCII字符。


    1 根据 MDC , \s码 [\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]

        3
  •  5
  •   jAndy    14 年前

    一个月前,这个行为被发布在jQuerys bugtracker上:

    http://dev.jquery.com/ticket/6605

    Andrew 谢谢你指给我看。