Get the Last Word of a String in JavaScript


Borislav Hadzhiev

Last updated: Oct 9, 2021


Photo from Unsplash

Get the Last Word from a String #

To get the last word of a string:

  1. Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string.
  2. Call the pop() method to get the value of the last element (word) in the array.
const str = 'An example sentence'; const lastWord = str.split(' ').pop(); console.log(lastWord); // 👉️ sentence

We use the String.split method to get an array containing the words in the string.

const str = 'An example sentence'; const split = str.split(' ') console.log(split) // ️👉️ ['An', 'example', 'sentence']

The parameter we pass to the split method is the separator, in our case we split the string on the space character.

Finally, we use the Array.pop method, which removes and returns the last element of an array - in our case the last word in the string.

Instead of using the pop method we can also access the array at its last index to get the last word.

const str = 'An example sentence'; const arr = str.split(' '); console.log(arr); // 👉️ ['An', 'example', 'sentence'] const lastWord = arr[arr.length - 1]; console.log(lastWord); // 👉️ sentence

This example is very similar to the Last, but instead of using the pop method, we use bracket notation to get the element at the last index of the array.

Indexes are zero based in JavaScript, therefore the Last element in an array has an index of 0 and the last element an index of arr.length - 1

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.