Get the First Word of a String in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20211 min read

banner

Photo by Cody Black

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 the space character, 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.

An alternative approach is to 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.

Accessing the array element at index 0 using bracket notation is perhaps a more direct an intuitive approach, but pick the one that works best for you.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee