views:

12072

answers:

2

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.

Cheers,
Steve

+18  A: 

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());
Andreas Grech
Correct but /\s/g would be a clearer pattern (the "i" is redundant and the ' ' is an unusual form - also fwiw a pattern of /(^\s*)|(\s*$)/g is equivalent to trim.
annakata
You are correct annakata, I removed the /i because it is redundant since case sensitivity in this case is not an issue
Andreas Grech
One thing to be wary of is that IE doesn't consider non-breaking spaces ( ,  ,  , \xA0, \u00A0, etc...) as white-space, so /[\s\xA0]+/g might be more reliable for replacing all white-space.
travis
+15  A: 

Actually, jQuery has a built in trim function:

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

See here for details.

Tuxmentat