Javascript: Returning the last word in a string

83,927

Solution 1

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

}

Solution 2

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

Solution 3

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

Solution 4

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.

Solution 5

Adding from the accepted answer, if the input string is "Hello World " (note the extra space at the end), it will return ''. The code below should anticipate in case user fat-fingered " ":

var lastWord= function(str) {
  if (str.trim() === ""){
    return 0;
  } else {   
    var splitStr = str.split(' ');
    splitStr = splitStr.filter(lengthFilter);
    return splitStr[splitStr.length - 1];
  }
};

var lengthFilter = function(str){
    return str.length >= 1;
};
Share:
83,927
Andrew P
Author by

Andrew P

Updated on February 20, 2022

Comments

  • Andrew P
    Andrew P about 2 years

    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)

  • chris.nesbit1
    chris.nesbit1 almost 9 years
    short, clean, no mess no fuss.
  • Roman Sklyarov
    Roman Sklyarov over 8 years
    It is possible to replace splice(-1)[0] by pop()
  • twobob
    twobob about 8 years
    you would have to trim() a trailing space makes this bomb
  • Benjamin W.
    Benjamin W. about 8 years
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
  • now_world
    now_world about 6 years
    Note this will not work for a string with a space at the end ("Hello World ").split(" "); returns ["Hello", "World", ""]. Where the "last word" would be "".
  • Jyoti Prakash
    Jyoti Prakash almost 6 years
    Use can do this words.trim().split(" ");
  • Sturm
    Sturm over 3 years
    Very long time ago.. but..If you would like to remove any extra spaces in between words use instead: data.split(/\s+/).splice(-1));
  • dotnethaggis
    dotnethaggis almost 3 years
    I'd use words.split as you don't need to know the position of the space. You're giving yourself more work.