Question

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 http://bit.ly/9B0Xon

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

Was it helpful?

Solution

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

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

OTHER TIPS

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

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); 
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top