views:

414

answers:

4

I'm trying to call the jQuery text() function and run it through the trim() function to remove all trailing and leading whitespace. Seems to work great in Firefox, however, does not work in IE7 (refuses to remove a space trailing at the end).

Any ideas?! Maybe a regex solution?

A: 

Yes i have an idea. The whitespace at the end is not in the element you are calling your text() function on. This can happen in IE because it treats whitespace differently then firefox, and will give it its own elements, where as firefox will not. This is just a hunch, because your question doesnt give much to go on.

mkoryak
This doesn't make sense. It's a simple string - the origin of the whitespace is irrelevant.
SLaks
no, it wouldnt make sense if trim didnt work on a string, its a simple regex, it should work.
mkoryak
i think that a text returns a string not the nodes/elements you are refering to unless he has used html instead of text lol the answer is irrelevant
Val
+3  A: 

you most probably have forgotten about jquery chainning ...

try this

$('#selector').trim($('#selector').text())

don't be lazy with

$('#selector').text().trim();//this is wrong...

Val
If i was selecting incorrectly, would that explain why this would be working in Firefox, but not in IE?
YourMomzThaBomb
maybe u should update your answer with an example of the script, it was only a suggestion, as to your ie7 problem... or use an if statement with a substr(-1,1) to check if the last letter is a white space
Val
More easier: $.trim()
Laserson
A: 

jquery uses /^\s+|\s+/g in its trim method-

Any trailing space would have to be added after it returns.

It may depend on when you read it- try to alert the value directly from the trim operation. If that reads correctly, the space is being added by whatever you do next to the string.

If trim really returns with a trailing space, use text.replace( /^\s+|\s+/g,'').

kennebec
A: 

So here's the gist of what was going on. I had some text in a span element and after that text there was a hyperlink/image the user could click to remove the text from the line it was on (see code below). However, I had put a   after the span element text (in the hyperlink's text) to put a bit of padding between the span text and the "delete" image. So even though I was accessing the element's text and trimming $.trim($(this).parent().text()); it would still include that space at the end! Once I removed this extra space, things worked fine. Still no idea why $.trim() wouldn't take care of it though?!

<div>
  <span>
    <strong>SomeText</strong>
  </span>
  <a href="javascript:void(0);" onclick="removeMe();">&nbsp;
    <img src="delete.png" width="15" height="15" border="0" name="imgRemove" />
  </a>
</div>
YourMomzThaBomb
@yourmom your username is soooooooooooooooooooooooooooooooooooooo offensive
i am a girl