How to stop jQuery from returning tabs and spaces from formated code on .html() .val() .text() etc

I've got an html 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:



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!


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

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

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:


You can trim all the white space using this combination:

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

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

Need Your Help

Toggle button to switch between two fragments

android android-fragments toggle

I have a swipe view app I am currently developing. On one of my swipe views, is it possible to have a list view in one fragment and when a toggle button is switched, switch to another fragment on the

PHP SDK library api return blank result

php facebook sdk github

I have successfully install the domain, already able to login through Facebook, already get these params,