Sam Provides
Sam Provides

Reputation: 259

charAt first letter of last word in a string

I am trying to select the first letter of the last word in a string: such as the first letter after the last space.

"Hello World" I need to select "W" "Hello World I am young" need to select "y"

using charAt()

thanks

Upvotes: 0

Views: 1434

Answers (4)

Jason Saruulo
Jason Saruulo

Reputation: 1897

If you are just allowed to use charAt do the following:

Iterate through the whole string and always remember the last position you have found an empty space. If you are at the end of the string take the char next to the position you have remembered for the last empty space you have found.

Be aware of the case that your string ends with an empty space. If this could be the case you will probably need two indexes. Also take care if your string does not contain any empty space.

Upvotes: 0

isvforall
isvforall

Reputation: 8926

Using lastIndexOf function:

var str = "Hello World";
str.charAt(str.lastIndexOf(' ') + 1)

Upvotes: 2

millerbr
millerbr

Reputation: 2961

A string is just an array of characters, so you can access it with square brackets. In order to get the first letter of each word in your string, try this:

var myString = "Hello World"
var myWords = myString.split(" ");
myWords.forEach(function(word) {
    console.log(word[0]);
});

For just the last word in a string:

var myString = "Hello World"
var myWords = myString.split(" ");
console.log(myWords[myWords.length-1][0]);

Upvotes: 0

madox2
madox2

Reputation: 51861

You can split string by empty space, pop last element and ask for it's first letter:

"Hello World".split(" ").pop().charAt(0); // W

Upvotes: 5

Related Questions