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/

Answers


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


Need Your Help

How to wrap executable .war with embedded tomcat into .exe?

java spring-mvc spring-boot launch4j embedded-tomcat-8

I have standalone web application, uses embedded Tomcat, MVC Spring boot.

Bing maps API key (credentials)

api bing-maps credentials

is there anyway to protect the Bing maps API key from being exposed to the client?