Skip to main content

How to Get the First Word of a String in JavaScript

Extracting the first word from a sentence or a multi-word string is a common text manipulation task. The most robust and reliable way to do this is by finding the first space in the string and taking all the characters before it. However, a simpler approach using split() is also very common.

This guide will teach you the two primary methods for this task. We'll cover the safe and efficient approach using indexOf() and slice(), as well as the more popular but slightly less performant split() method, explaining the trade-offs of each.

The Core Problem: Handling Spaces and Edge Cases

A "word" is typically a sequence of characters separated by a space. The main challenge is to correctly handle strings that might have leading spaces or multiple spaces between words.

For example, , how to reliably get the first word ("Hello") from these strings?

// Problem: How to reliably get the first word ("Hello") from these strings?
const str1 = 'Hello World';
const str2 = ' Hello World'; // Has leading spaces

The split() Method (Simple and Readable)

The most intuitive method is to split the string into an array of words and then take the first element.

The logic:

  1. Use str.trim() to remove any leading or trailing whitespace. This is a crucial first step.
  2. Use str.split(' ') to break the string into an array of words, using a single space as the delimiter.
  3. Take the first element of the resulting array at index 0.

This solutionis very readable and easy to understand.

function getFirstWord(str) {
// Trim the string to handle leading spaces
const trimmedStr = str.trim();

if (trimmedStr === '') {
return '';
}

// Split the string by space and take the first element
return trimmedStr.split(' ')[0];
}

// Example Usage:
console.log(getFirstWord('Hello World')); // Output: "Hello"
console.log(getFirstWord(' Hello World')); // Output: "Hello"
console.log(getFirstWord('')); // Output: ""

The indexOf and slice Method (More Performant)

A more efficient method avoids creating an intermediate array. It works by finding the position of the first space and extracting the substring before it.

The logic:

  1. Use str.trim() to handle leading spaces.
  2. Use str.indexOf(' ') to find the index of the first space.
  3. If no space is found, the whole string is the first word.
  4. If a space is found, use str.slice(0, index) to get the substring from the beginning of the string up to that index.

Solution:

function getFirstWord(str) {
const trimmedStr = str.trim();
const indexOfFirstSpace = trimmedStr.indexOf(' ');

// If no space is found, the whole string is the first word
if (indexOfFirstSpace === -1) {
return trimmedStr;
}

// Otherwise, slice the string from the beginning to the first space
return trimmedStr.slice(0, indexOfFirstSpace);
}

// Example Usage:
console.log(getFirstWord('Hello World')); // Output: "Hello"
console.log(getFirstWord(' Hello World')); // Output: "Hello"
console.log(getFirstWord('Hello')); // Output: "Hello"

Why indexOf and slice is Often Better

While both methods work, the indexOf and slice approach is generally considered a better practice for a few key reasons:

  • Performance: It is more performant, especially for very long strings. It only needs to scan the string until it finds the first space, whereas split() must traverse the entire string to create an array of all words, which is unnecessary work.
  • Memory Efficiency: It does not create an intermediate array, which can be a small advantage in memory-constrained environments.

For most day-to-day use, the performance difference is negligible, and the split() method's readability is a strong advantage. However, for performance-critical code, the indexOf/slice combination is superior.

Conclusion

For getting the first word of a string, JavaScript offers two excellent solutions.

  • The .trim().split(' ')[0] method is the most readable and intuitive approach. It is perfect for most use cases where absolute performance is not a concern.
  • The .trim(), indexOf(), and slice() combination is a more performant and memory-efficient solution. It is the recommended best practice for performance-critical applications or when working with very large strings.

Regardless of the method you choose, always use .trim() first to ensure your logic correctly handles strings with leading whitespace.