Get the First Word of a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the First Word of a String #

To get the first word of a string:

  1. Call the split() method 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. Access the array at index 0 to get the first word of the string.
index.js
const str = 'Hello world'; const first = str.split(' ')[0] console.log(first); // 👉️ Hello

The String.split method splits a string into an array, based on a provided separator.

index.js
const str = 'Hello world'; const split = str.split(' ') console.log(split) // 👉️ ['Hello', 'world']

By splitting the string on each space, we get an array containing the words in the string.

The final step is to access the array element (word) at index 0.

Indexes are zero-based in JavaScript, meaning the index of the first element in the array is 0 and the index of the last element is arr.length - 1.

Alternatively, we can use the shift() method on the array to get its first element.

index.js
const str = 'Hello world'; const first = str.split(' ').shift(); console.log(first); // 👉️ Hello

The Array.shift method removes and returns the first element from an array.

Which approach you pick is a matter of personal preference. I'd go with the direct index access as I find it more readable and intuitive.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.