0

I have the following JQUERY Function:

function siteCounterUpdate(n) {
    $('ul#indexSiteCounterBottom').empty();
    for(i=0;i<9;i++) {

            //alert(n.toString()[i]);

      $('ul#indexSiteCounterBottom').append('<li>'+n.toString()[i]+'</li>');
      $('ul#indexSiteCounterBottom li:nth-child(3n)').addClass('extra-margin');
    }
}

The function receives a number (string) and if its 9 characters long it works perfectly. 9 is the full length.

However if the number is say 7 characters long I need the first 2 items to be replaced with a HTML no breaking space.

&nbsp; 

I'm struggling to understand how I can do this.

eg: 6 character long string would be 1. nbsp 2. nbsp 3. nbsp 4 - 9. the string.

any advice would be great.

thx

Adam
  • 19,932
  • 36
  • 124
  • 207

4 Answers4

3

Here's how to pad a string:

function padString (str, len, padWith) {
    var padLength = len - str.length;
    return padLength < 1 ? str : Array(padLength + 1).join(padWith) + str;
}

Sample usage:

padString('1234567899', 9, '&nbsp;'); // "1234567899"
padString('123456789', 9, '&nbsp;');  // "123456789"
padString('12345678', 9, '&nbsp;');   // "&nbsp;12345678"
padString('1234567', 9, '&nbsp;');    // "&nbsp;&nbsp;1234567"
padString('234567', 9, '&nbsp;');     // "&nbsp;&nbsp;&nbsp;234567"

Here's the fiddle: http://jsfiddle.net/8JdwP/

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

You can use a couple of for loops like so to count between n and 9 for your &nbsp;'s and 0 and n for your string:

function siteCounterUpdate(n) {
    var target = $('ul#indexSiteCounterBottom').empty();

    for (var i=n.length;i<9;i++) {
        target.append('<li>&nbsp;</li>');
    }

    // `i` doesn't have to be declared again because there's no block
    // scope in JavaScript, but I think it looks ugly otherwise :(.
    for (var i=0;i<n.length;i++) {
        target.append('<li>' + n + '</li>');
    }
}
Matt
  • 74,352
  • 26
  • 153
  • 180
1

I might be confused about what you want, but could you just right-align the counter so you don't need the spaces?

If not, you could create a pad function like described here.

Community
  • 1
  • 1
herbalcell
  • 31
  • 5
0
while (yourString.length < 9)
{
    yourString = "\u00A0" + yourString;   
}

demo

kei
  • 20,157
  • 2
  • 35
  • 62