1

Im using soundclouds api to echo out track information but I'd like to limit the amount of characters shown for each track title result to just 24 chars? I'd also like to be able to set both the track title and artist title to be displayed as capitalised text (first letter capital rest lowercase)

Thanks

 <li><a href="' + track.permalink_url +'">Track: ' + track.title + '<BR>Artist: '+ track.user.username + '</a></li>'
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
Dan Farrell
  • 105
  • 1
  • 1
  • 4

3 Answers3

3

Try this:

function formatter(str) {
    if(str.length < 24) {
      return str;
    } else {
      return str.charAt(0).toUpperCase() + str.substr(1,23) + '..';
    }   
}

<li><a href="' + track.permalink_url +'">Track: ' + formatter(track.title) + '<BR>Artist: '+ formatter(track.user.username) + '</a></li>'

DEMO

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • Thank you but I dont want uppercase, I need capitalise so its only the first letter thats a captial? also how can add a "..." to the end of the title? – Dan Farrell May 06 '12 at 12:36
0

For part 1 of your question, look at substr method. It's a standard method on all JavaScript String objects.

For part 2, capitalizing, check out this question.

Community
  • 1
  • 1
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
0

You can prepare the short title in advance, first taking the substring and making sure it is lower case:

var shortTitle = track.title.substr(0,24).toLowerCase();

Then use the following to upper case the first letter and use the rest of the lowercase string, adds ...:

// ... HTML ouput by JS ...

document.write(shortTitle.charAt(0).toUpperCase() + shortTitle.slice(1));

if (shortTitle.length > 24)
    document.write('...');

// ... HTML output by JS ...

Here in an example.

You can repeat these steps for the author.

Tamara Wijsman
  • 12,198
  • 8
  • 53
  • 82