How to Get the Last Word of a String in JavaScript
Extracting the last word from a string or sentence is a common text manipulation task. You might need to get a user's last name from a full name, or the final word from a sentence for analysis.
This guide will teach you the modern, standard methods for solving this problem. You will learn the most readable and robust approach using split() and trim(), and a more performant alternative using lastIndexOf() and slice().
The Core Method (Recommended): trim(), split(), and pop()
This is the most intuitive and readable approach. It leverages a chain of simple, descriptive methods.
The logic:
trim(): First, remove any leading or trailing whitespace from the string. This is a crucial step to prevent errors if the string ends with a space.split(' '): Split the cleaned string into an array of words using the space character as the delimiter.pop(): Call thepop()method on the resulting array. This method removes and returns the last element of the array, which is our last word.
For example, we want to get the last word from a sentence.
// Problem: How to get "sentence" from this string?
const str = 'An example sentence';
Solution:
function getLastWord(str) {
// 1. Trim whitespace
const trimmedStr = str.trim();
// 2. Split into an array of words
const words = trimmedStr.split(' ');
// 3. Get the last element
return words.pop();
}
// Example Usage:
console.log(getLastWord('An example sentence'));
// This handles trailing spaces correctly because of trim()
console.log(getLastWord('An example sentence '));
Output:
sentence
sentence
This can also be written as a clean one-liner:
const lastWord = str.trim().split(' ').pop();
An Alternative Method (More Performant): lastIndexOf() and slice()
For performance-critical code that processes a very large number of strings, this method can be slightly faster as it avoids creating an intermediate array.
The logic:
- Find the index of the last space in the string using
lastIndexOf(' '). - Use
slice()to extract the portion of the string that comes after that last space.
Solution:
function getLastWord(str) {
const trimmedStr = str.trim();
const lastSpaceIndex = trimmedStr.lastIndexOf(' ');
// Slice from the character after the last space to the end
return trimmedStr.slice(lastSpaceIndex + 1);
}
// Example Usage:
console.log(getLastWord('An example sentence'));
Output:
sentence
While this method is performant, it can be slightly less intuitive to read than the split() and pop() approach.
A Note on Robustness: Handling Multiple Spaces
A simple split(' ') can produce empty strings in its array if there are multiple spaces between words.
Problem:
const str = 'An example with multiple spaces';
// This results in empty strings in the array
console.log(str.split(' '));
// Output: ['An', 'example', '', 'with', '', '', 'multiple', 'spaces']
In this case, pop() would correctly return "spaces", but if the string ended with multiple spaces (and we didn't trim() it), pop() would return "".
A Robust Solution to handle all whitespace correctly: you can split by a regular expression (/\s+/) which means "one or more whitespace characters."
function getLastWord(str) {
const words = str.trim().split(/\s+/);
return words.pop();
}
console.log(getLastWord('An example with multiple spaces')); // Output: "spaces"
This is the most robust version of the split() approach.
Conclusion
Getting the last word of a string is a simple task with a few excellent solutions in JavaScript.
- The
str.trim().split(/\s+/).pop()pattern is the most robust and readable approach for most use cases. It clearly expresses the intent and correctly handles various whitespace issues. - The
lastIndexOf()andslice()combination is a more performant alternative that is great for performance-critical scenarios, though it can be slightly less intuitive.
For most day-to-day coding, the readability and robustness of the split() method make it the recommended best practice.