Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I strip white space when grabbing text with jQuery?

Tags:

jquery

I'm wanting to use jQuery to wrap a mailto: anchor around an email address, but it's also grabbing the whitepace that the CMS is generating.

Here's the HTML I have to work with, the script as I have it and a copy of the output.

HTML

<div class="field field-type-text field-field-email">
  <div class="field-item">
    [email protected]    </div>
</div>

jQuery JavaScript

$(document).ready(function(){
  $('div.field-field-email .field-item').each(function(){
    var emailAdd = $(this).text();
      $(this).wrapInner('<a href="mailto:' + emailAdd + '"></a>');
   });
 });

Generated HTML

<div class="field field-type-text field-field-email">
  <div class="field-items"><a href="mailto:%0A%20%20%20%[email protected]%20%20%20%20">
    [email protected]    </a></div>
</div>

Though I suspect that others reading this question might want to just strip the leading and tailing whitespace, I'm quite happy to lose all the whitespace considering it's an email address I'm wrapping.

like image 682
Steve Perks Avatar asked Dec 11 '08 19:12

Steve Perks


People also ask

How do I remove spaces between words in jQuery?

The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.

How do you remove spaces in input?

replace(/ +?/g, '')); }); This will remove spaces as you type, and will also remove the tab char.

How do you remove white spaces from front back of string?

JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.


4 Answers

Use the replace function in js:

var emailAdd = $(this).text().replace(/ /g,'');

That will remove all the spaces

If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :

var emailAdd = $.trim($(this).text());
like image 121
Andreas Grech Avatar answered Oct 22 '22 00:10

Andreas Grech


Javascript has built in trim:

str.trim()

It doesn't work in IE8. If you have to support older browsers, use Tuxmentat's or Paul's answer.

like image 34
Jhankar Mahbub Avatar answered Oct 22 '22 02:10

Jhankar Mahbub


Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

like image 27
Tuxmentat Avatar answered Oct 22 '22 00:10

Tuxmentat


str=str.replace(/^\s+|\s+$/g,'');

like image 42
Paul Avatar answered Oct 22 '22 01:10

Paul