Javascript: Returning the last word in a string

Try this:

you can use words with n word length.

example:

  words = "Hello World";
  words = "One Hello World";
  words = "Two Hello World";
  words = "Three Hello World";

All will return same value: "World"

function test(words) {
    var n = words.split(" ");
    return n[n.length - 1];

}

var data = "Welcome to Stack Overflow";
console.log(data.split(" ").splice(-1));

Output

[ 'Overflow' ]

This works even if there is no space in the original string, so you can straight away get the element like this

var data = "WelcometoStackOverflow";
console.log(data.split(" ").splice(-1)[0]);

Output

WelcometoStackOverflow

You could also:

words.split(" ").pop();

Just chaining the result (array) of the split function and popping the last element would do the trick in just one line :)