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
splitmethod will return an array containing the words in the string.
0to get the first word of the string.
const str = 'Hello world'; const first = str.split(' ') 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
0and 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
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.
0using bracket notation is perhaps a more direct an intuitive approach, but pick the one that works best for you.