Skip to content

How to Get the Last Word of a String in JavaScript

Learn how to extract the last word from a string in JavaScript using the most reliable methods like trim(), split(), and pop() for readability or lastIndexOf() and slice() for performance.

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().

This is the most intuitive and readable approach. It leverages a chain of simple, descriptive methods.

The logic:

  1. 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.
  2. split(' '): Split the cleaned string into an array of words using the space character as the delimiter.
  3. pop(): Call the pop() 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

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:

  1. Find the index of the last space in the string using lastIndexOf(' ').
  2. 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

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']

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"

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() and slice() 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.

Navigation