71

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)

7
  • 13
    sentence.split(" ").slice(-1) Commented Jan 2, 2014 at 12:51
  • lastIndexOf and slice! Commented Jan 2, 2014 at 12:51
  • I don't get it. You have already solved your problem in the question. What do you expect us to do? Commented Jan 2, 2014 at 12:51
  • @Blender post an answer. Commented Jan 2, 2014 at 12:51
  • 1
    @GrijeshChauhan: It's not an interesting question. Commented Jan 2, 2014 at 12:52

12 Answers 12

79

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

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 "".
Use can do this words.trim().split(" ");
73

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

1 Comment

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.
39
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

3 Comments

It is possible to replace splice(-1)[0] by pop()
you would have to trim() a trailing space makes this bomb
Very long time ago.. but..If you would like to remove any extra spaces in between words use instead: data.split(/\s+/).splice(-1));
12

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.

1 Comment

short, clean, no mess no fuss.
4

To complete Jyoti Prakash, you could add multiple separators (\s|,) to split your string (via this post)

Example:

function lastWord(words) {
  var n = words.split(/[\s,]+/) ;
  return n[n.length - 1];
}

Note: regex \s means whitespace characters : A space character, A tab character, A carriage return character, A new line character, A vertical tab character, A form feed character

snippet

var wordsA = "Hello  Worlda"; // tab
var wordsB = "One Hello\nWorldb";
var wordsC = "Two,Hello,Worldc";
var wordsD = "Three Hello Worldd";

function lastWord(words) {
  var n = words.split(/[\s,]+/);
  return n[n.length - 1];
}


$('#A').html( lastWord(wordsA) );
$('#B').html( lastWord(wordsB) );
$('#C').html( lastWord(wordsC) );
$('#D').html( lastWord(wordsD) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A:<span id="A"></span><br/>
B:<span id="B"></span><br/>
C:<span id="C"></span><br/>
D:<span id="D"></span><br/>

Comments

2

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

Comments

1

Easiest way is to use slice method:-

For example:-

let words = "hello world";
let res = words.slice(6,13);
console.log(res);

1 Comment

I'd use words.split as you don't need to know the position of the space. You're giving yourself more work.
1

According to me the easiest way is:

lastName.trim().split(" ").slice(-1)

It will give the last word in a phrase, even if there are trailing spaces. I used it to show the last name initials. I hope it works for you too.

Comments

0
/**
 * Get last word from a text
 * @param {!string} text
 * @return {!string}
 */
function getLastWord(text) {
  return text
    .split(new RegExp("[" + RegExp.quote(wordDelimiters + sentenceDelimiters) + "]+"))
    .filter(x => !!x)
    .slice(-1)
    .join(" ");
}

Comments

0

Just use .slice and .lastIndexOf in JavaScript. Its pretty simple to use.

const a = "Bringing founders's ideas to life";
const b = a.lastIndexOf(" ");
const word = a.slice(b, a.length);
console.log(word);

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

Use split()

function lastword(words){
 array = words.split(' ');

 return array[1]
}

Comments

-1

Its pretty straight forward. You have got two words separated by space. Lets break the string into array using split() method. Now your array has two elements with indices 0 and 1. Alert the element with index 1.

var str="abc def";
var arr=str.split(" ");
alert(arr[1]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.