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

Jquery

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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());

Solution 2 - Jquery

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.

Solution 3 - Jquery

Actually, jQuery has a built in trim function:

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

See here for details.

Solution 4 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve PerksView Question on Stackoverflow
Solution 1 - JqueryAndreas GrechView Answer on Stackoverflow
Solution 2 - JqueryJhankar MahbubView Answer on Stackoverflow
Solution 3 - JqueryTuxmentatView Answer on Stackoverflow
Solution 4 - JqueryPaulView Answer on Stackoverflow