Alex Rivera | Logout

jQuerys $.trim(), bug or poorly written?

Asked 2010-06-28T13:06:11.087
9

$.trim() uses the following RegExp to trim a string:

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

As it turns out, this can be pretty ugly, Example:

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

This code hangs Firefox and Chrome, it just takes like forever. "mystr" contains whitespaces but mostly hex 160(A0) characters. This "problem" does only occur, if there is no prepending whitespace/A0, but somewhere within the string. I have no clue why this happens.

This expression:

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

just works fine in all tested scenarios. Maybe a better pattern for that?

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

UPDATE

It looks like you can't copy&paste this example string, at some points those A0 characters are replaced. Firebug console will also replace the characters on pasting, you have to create your own string in a sepperate html file/editor to test this.

Edit
Report

1 Answer

7

Normally an expression like ^\s+|\s+$ should be enough for trimming, since \s is supposed to match all space characters, even \0xa0 non-breaking spaces1. This expression should run without causing any problems.

Now probably some browser that jQuery wants to support doesn't match \0xa0 with \s and to work around this problem jQuery added the alternative (\s|\0xa0), to trim away non-breaking spaces on that browser too.

With this change, the second part of the regex looks like (\s|\0xa0)+$, which leads to problems in browsers where \0xa0 is also matched by \s. In a string containing a long sequence of \0xa0 characters, each character can be matched by \s or \0xa0, leading to lots of alternative matches and exponentially many combinations how different matches can be combined. If this sequence of \0xa0 characters is not at the end of the string, the trailing $ condition can never be fulfilled, no matter which spaces are matched by \s and which are matched by \0xax, but the browser doesn't know this and tries all combinations, potentially searching for a very long time.

The simplified expression you suggest will not be sufficient since \s is supposed to match all unicode space characters, not just the well-known ASCII ones.


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

answered 2010-06-28T13:53:00.620

Your Answer