5

How can I trim all spaces from a string, even when they are caused by a non-breaking spaces ( )

For example:

var foo = $.trim($('<p>&nbsp;foo&nbsp;</p>').text());

The value of foo is " foo " instead of "foo"

UPDATE So, the problem wasn't jQuery's trim function. It works great. The problem is MSAjax's trim function. jQuery, rightly, uses function detection and if they don't exist, uses it's implementation.

Unfortunately, MSAJax's implementation of trim doesn't strip char 160 (non breaking space). However, the jQuery regex trim does, as it realizes that IE doesn't include char 160 in \s.

Why do stupid browser problems always end up being an issue with how M$ implements something???

2

3 Answers 3

3

So, the problem wasn't jQuery's trim function. It works great. The problem is MSAjax's trim function. jQuery, rightly, uses function detection and if they don't exist, uses it's implementation.

Unfortunately, MSAJax's implementation of trim doesn't strip char 160 (non breaking space). However, the jQuery regex trim does, as it realizes that IE doesn't include char 160 in \s.

Why do stupid browser problems always end up being an issue with how M$ implements something???

1
  • Is there a way to bypass M$ implementation and force jQuery's trim?
    – jbyrd
    Nov 8, 2016 at 17:42
1

Are you sure about that? I tried a slightly modified version of your snippet just now:

var foo = $.trim($('<p>&nbsp;foo&nbsp;</p>').text());
alert('#' + foo + '#');

and there were no spaces on either side of the 'foo'. http://jsfiddle.net/Ux7Wc/

This was using jQuery 1.6.2 in Firefox 5.

3
  • I'm not so sure anymore...it's not working in code, and I'm looking at the values in the debugger and this is what appears to be happening. But in jsfiddle I can't replicate the problem
    – CaffGeek
    Sep 14, 2011 at 15:28
  • The problem is IEs native trim (Which jquery uses if it exists) doesn't strip char 160, which is what an nbsp is transformed too
    – CaffGeek
    Sep 14, 2011 at 16:29
  • Correction, it's not IE's native trim, but MSAjax's trim function
    – CaffGeek
    Sep 14, 2011 at 17:39
1

This is a bug before JQuery 1.4. Please upgrade.

http://bugs.jquery.com/ticket/4980

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.