Javascript: Returning the last word in a string

Viewed 93661

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)

11 Answers

Easiest way is to use slice method:-

For example:-

let words = "hello world";
let res = words.slice(6,13);
console.log(res);
/**
 * 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(" ");
}

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.

Related