Javascript: Returning the last word in a string

JavascriptStringSubstring

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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/>

Solution 6 - Javascript

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

Solution 7 - Javascript

Easiest way is to use slice method:-

For example:-

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

Solution 8 - Javascript

/**
 * 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(" ");
}

Solution 9 - Javascript

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.

Solution 10 - Javascript

Use split()

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

 return array[1]
}

Solution 11 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew PView Question on Stackoverflow
Solution 1 - JavascriptJyoti PrakashView Answer on Stackoverflow
Solution 2 - Javascriptuser5505115View Answer on Stackoverflow
Solution 3 - JavascriptthefourtheyeView Answer on Stackoverflow
Solution 4 - JavascriptPaul S.View Answer on Stackoverflow
Solution 5 - Javascriptboly38View Answer on Stackoverflow
Solution 6 - JavascriptIggyView Answer on Stackoverflow
Solution 7 - JavascriptRonak KhangaonkarView Answer on Stackoverflow
Solution 8 - JavascriptZuhair TahaView Answer on Stackoverflow
Solution 9 - Javascriptsalvi shahzadView Answer on Stackoverflow
Solution 10 - JavascriptEupheView Answer on Stackoverflow
Solution 11 - JavascriptSatyapriya MishraView Answer on Stackoverflow