1

I am theming a JSP app that has a table header with dynamically generated data (I think it's called Jasper Reports?) and I don't have access to any template files for the output. I've gotten things to look pretty good with a little JQuery foo.

But I am still having one issue, there seems to be white space in some span tags within the headers td > spans:

<td><span> My Heading</span></td>

Note the white space before the word "My".

I found this nifty bit of code to trim white space but the issue is that it takes all white space out.

var pane = $('span');
pane.val($.trim(pane.val()).replace(/\s*[\r\n]+\s*/g, '\n')
    .replace(/(<[^\/][^>]*>)\s*/g, '$1')
    .replace(/\s*(<\/[^>]+>)/g, '$1'));

So now using this code, it ends up as:

   <td><span>MyHeading</span></td>

Ideally I would like to modify it so just the first bit of white space is removed but none after that.

Community
  • 1
  • 1
Danny Englander
  • 2,005
  • 5
  • 26
  • 41

3 Answers3

5

Try this:

.replace(/^\s+/g, "");

That should trim any whitespace at the beginning of the string. Alternatively, you can make it trim trailing whitespace using a slightly different expression. See here:

http://www.toptip.ca/2010/02/javascript-trim-leading-or-trailing.html

Here's the example so you can see how it works: http://jsfiddle.net/CkMPH/

opes
  • 1,778
  • 1
  • 16
  • 22
5

Use .text() to get the string value.

var pane = $('span');
pane.html($.trim(pane.text()));

http://jsfiddle.net/gaboesquivel/cHevR/

Edit: the above code won't work as it overwrites the text if it there's more than 1 span in the document

You need to iterate the array of spans

//array of all the spans that are children of a td element
var spansArray = $('td > span');
//iterate the array
spansArray.each(function() {
    var $this = $(this);
    $this.html($.trim($this.text()));
});​

http://jsfiddle.net/gaboesquivel/cHevR/2/

Pattle
  • 5,983
  • 8
  • 33
  • 56
Gabo Esquivel
  • 3,494
  • 2
  • 23
  • 18
  • Your code in the fiddle is different than what is here, which should I use? – Danny Englander Feb 16 '12 at 00:40
  • the one I posted here will affect all spans on your document, the one on fiddle will affect only the spans with class "changeMe", since you don't have access to the html you will have to select all spans `$('span')` unless you find a way to select the specific set you want to change. `$('#myModuleId span')` for instance @see [JQuery Selectors](http://api.jquery.com/category/selectors/) – Gabo Esquivel Feb 16 '12 at 00:48
  • try `$('td > span')` = child span of all td elements – Gabo Esquivel Feb 16 '12 at 01:17
1

For the only first space to be removed you need that code

var pane = $('span');
pane.text(pane.text().replace(/^\s/, ''));

http://jsfiddle.net/P9jSL/

Cheery
  • 16,063
  • 42
  • 57