How to strip white space when grabbing text with jQuery

by 0

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.
<div >
  <div >    </div>
jQuery JavaScript
  $('div.field-field-email .field-item').each(function(){
    var emailAdd = $(this).text();
      $(this).wrapInner('<a href="mailto:' + emailAdd + '"></a>');
Generated HTML
<div >
  <div ><a href="">    </a></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.

This is the solution

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

Leave a Reply