John the Painter
John the Painter

Reputation: 2615

Get first letter of last word of each span

I'm trying to get the first letter of the last word in every span on the page. I will then add this as a class (used for filtering).

Here is what I have so far:

$('.each-artist span').each(function() {
    var artistName = $(this).text().toLowerCase(); // get text, convert to lowercase
    var firstLetterSplice = artistName.slice(0, 1); // get first letter
    $(this).parent().parent('.each-artist').addClass(firstLetterSplice); // add as class
});

So, this works fairly successfully, it takes the text of each .each-artist span, lowercases it, splices it to find first letter then adds this first letter as a class.

The only issue is I need to get the last word of each .each-artist span, not the first, then get the first letter of this last word and apply it as a class.

I have a jsFiddle set up for testing: http://jsfiddle.net/rZbwQ/

Upvotes: 1

Views: 566

Answers (1)

adeneo
adeneo

Reputation: 318212

You're almost there, just split by word boundary and then get the last word

$('.each-artist span').each(function () {
    var artistName = $(this).text().toLowerCase().split(/\b/);
    var firstLetterSplice = artistName.pop().slice(0, 1);
    $(this).closest('.each-artist').addClass(firstLetterSplice);
});

FIDDLE

Upvotes: 4

Related Questions