Borislav Hadzhiev
Sat Oct 09 2021·2 min read
Photo by Michael Baldovinos
To get the last word of a string:
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.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.
0
and the last element an index of arr.length - 1