How to stop jQuery from returning tabs and spaces from formated code on .html() .val() .text() etc
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 for开发者_如何学JAVAmatted 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!
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:
<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);
});
精彩评论