Javascript: Returning the last word in a string

right to it:

I have a words string which has two words in it, and i need to return the last word. They are seperated by a " ". How do i do this?

function test(words) {

var n = words.indexOf(" ");
var res = words.substring(n+1,-1);
return res;

}

I've been told to use indexOf and substring but it's not required. Anyone have an easy way to do this? (with or without indexOf and substring)


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];

}

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 :)


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 want the last word, which suggests lastIndexOf may be more efficient for you than indexOf. Further, slice is also a method available to Strings.

var str = 'foo bar fizz buzz';
str.slice(
    str.lastIndexOf(' ') + 1
); // "buzz"

See this jsperf from 2011 showing the split vs indexOf + slice vs indexOf + substring and this perf which shows lastIndexOf is about the same efficiency as indexOf, it mostly depends on how long until the match happens.