#7477 closed bug (duplicate)
String with several non-breaking-space chars in the middle breaks trim()
Reported by: | anonymous | Owned by: | |
---|---|---|---|
Priority: | undecided | Milestone: | 1.5 |
Component: | unfiled | Version: | 1.4.3 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
The trim() function uses this regex:
/^(\s|\u00A0)+|(\s|\u00A0)+$/g
This is intended to handle both normal whitespace characters, as well as the Unicode character for non-breaking spaces. (\u00A0 or charcode 160).
This regex triggers the "unresponsive script" error in Firefox and Chrome when run on a string that has several successive non-breaking-space characters in the middle (not leading or trailing). It appears to be the part for trailing whitespace that is triggering this bug in the browsers.
This breaks:
// Create a string with a bunch of non-breaking spaces in the middle var arr = []; for (var i = 0; i < 30; i++) { arr.push(160); } var str = 's' + String.fromCharCode.apply(null, arr) + 's'; // Try to right trim with JQuery's regex str.replace(/(\s|\u00A0)+$/g, '');
Doing it in two passes works:
// Create a string with a bunch of non-breaking spaces in the middle var arr = []; for (var i = 0; i < 30; i++) { arr.push(160); } var str = 's' + String.fromCharCode.apply(null, arr) + 's'; // Try to right trim with JQuery's regex str.replace(/(\s)+$/g, '').replace(/(\u00A0)+$/g, '');
One way to fix would be for the trim() function to do the combined replace for leading whitespace, then to do the trailing replace in two passes.
This has been fixed already. If you use jQuery 1.4.3 you can verify that the error doesn't occur anymore.
For 1.4.3 several improvements related to the regex use where landed. Also the
trim()
function changed significantly. It now uses the nativeString.prototype.trim
function when available in the browser. If the fallback is used it does the trim in two steps now (check the diff forsrc/core.js
on this commit there you can nicely see howtrim()
has changed).