views:

41

answers:

3

I've got an html table:

<table><tr>
 <td>M1</td>
 <td>M2</td>
 <td>M3</td>
 <td>M4</td>
</tr></table>

and a simple jQ script:

$('td').click(function(){ alert( $(this).html() ); });

That works just fine.... but in the real world, I've got several hundred table cells and the code is formatted improperly in places because of several people editing the page.

So if the html is:

     <td>
                     M1         

             </td>

then the alert() is giving me all the tabs and returns and spaces:

Javascript Alert

What can I do to get ONLY the text without the tabs and spaces? I've tried .html(), .val(), .text() to no avail. Thanks!

+1  A: 

You can trim the string:

String.prototype.trim = function () {
    return this.replace(/^\s*/, '').replace(/\s*$/, '');
};

and use it like this:

$('td').click(function() { 
    var html = $(this).html().trim();
    alert(html); 
});
Darin Dimitrov
+4  A: 

jQuery has a built-in trim function, $.trim(), you can use it like this:

$('td').click(function() {  alert( $.trim($(this).html()) ); });
Nick Craver
For this project, this seems to be the ticket! Thanks!
brandonjp
+2  A: 

Nick and Darin posted a great way to trim the white space from the beginning and end of the content, but in case you have a lot of white space in the middle, say this as an example:

<div>
             M1
                                                  M2
     </div>

You can trim all the white space using this combination:

$('div').click(function() {
 var html = $.trim($(this).html().replace(/(\s+)/g,' '));
 alert(html);
})
fudgey