Borislav Hadzhiev
Sat Oct 09 2021·2 min read
Photo by Cody Black
To get the first word of a string:
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.0
to get the first word of the string.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.
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
.
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.
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.
0
using bracket notation is perhaps a more direct an intuitive approach, but pick the one that works best for you.