Get the Last Word of a String in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20211 min read

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.
index.js
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.

index.js
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.

index.js
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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee