Last updated: Mar 1, 2024
Reading timeยท3 min
To get the first word of a string in JavaScript:
String.split()
method to split the string into an array of words.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 the provided separator.
const str = 'Hello world'; const split = str.split(' ') console.log(split) // ๐๏ธ ['Hello', 'world']
We split the string on each space to get an array of the words in the string.
The last step is to access the array element (word) at index 0
.
0
and the index of the last element is arr.length - 1
.You can also use the Array.at()
method to get the first array element.
const str = 'Hello world'; const first = str.split(' ').at(0); console.log(first); // ๐๏ธ Hello
The Array.at() method takes an integer value and returns the item at that index.
If the index is not contained in the array, the method returns undefined
.
If your string starts with a space, use the String.trim()
method to remove
any leading and trailing whitespace characters before calling the
String.split()
method.
const str = ' Hello world'; const first = str.trim().split(' ')[0]; console.log(first); // ๐๏ธ Hello
String.trim()
method to remove the leading and trailing whitespace from the string and then called the String.split()
method.This is necessary because if the string starts with a whitespace character, the first element in the array would be an empty string.
const str = ' Hello world'; // ๐๏ธ [ '', 'Hello', 'world' ] console.log(str.split(' '));
Alternatively, we can use the Array.shift()
method.
This is a two-step process:
String.split()
method to split the string into an array of words.Array.shift()
method to remove and return the first element from
the array.const str = 'Hello world'; const first = str.split(' ').shift(); console.log(first); // ๐๏ธ Hello
We used the String.split()
method to split the string into an array of words.
const str = 'Hello world'; // ๐๏ธ [ 'Hello', 'world' ] console.log(str.split(' '));
The Array.shift() method removes and returns the first element from the array.
Alternatively, you can use the String.slice()
method.
This is a two-step process:
String.indexOf()
method to get the index of the first space in the
string.String.slice()
method to get the part of the string before the
first space.const str = 'Hello world'; const firstWord = str.slice(0, str.indexOf(' ')); console.dir(firstWord); // ๐๏ธ 'Hello'
We used the String.indexOf()
method to get the index of the first occurrence
of a space in the string.
const str = 'Hello world'; console.log(str.indexOf(' ')); // ๐๏ธ 5
We passed the following arguments to the String.slice() method:
The String.slice()
method returns the first word of the string or in other
words, the part of the string before the first space.
You can learn more about the related topics by checking out the following tutorials: