Home > Back-end >  What is the best way to get the last word of a string in javascript?
What is the best way to get the last word of a string in javascript?

Time:08-09

if i have a string like:

var myString = "word1 word2";
var lastWord;

how can i make it so lastWord = "word2"?

CodePudding user response:

Split it into an array based on the spaces, then get the last element

const myString = "word1 word2";
const lastWord = myString.split(" ").at(-1);
console.log(lastWord);

CodePudding user response:

Infinite ways to do that! Use a combination of split and pop

const lastWord = myString.split(' ').pop()

CodePudding user response:

you can achieve this with split() and pop():

const lastWord = myString.split(' ').pop();

CodePudding user response:

A regular expression that matches the word characters (\w ) before the end of a string ($) might be a good fit here.

match returns an array so just retrieve the first element.

const str = 'word1 word2 word3';
const lastWord = str.match(/\w $/)[0];
console.log(lastWord);

  • Related