Remove the First Word from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Remove the First Word from a String #

To remove the first word from a string, call the indexOf() method to get the index of the first space in the string. Then use the substring() method to get a portion of the string, with the first word removed.

index.js
function removeFirstWord(str) { const indexOfSpace = str.indexOf(' '); if (indexOfSpace === -1) { return ''; } return str.substring(indexOfSpace + 1); } console.log(removeFirstWord('Hello World')); // 👉️ World console.log(removeFirstWord('hello')); // 👉️ '' console.log(removeFirstWord('one two three')); // 👉️ two three

We created a reusable function that removes the first word from a string.

We used the String.indexOf method to get the index of the first space in the string.

The indexOf method returns the index of the first occurrence of a substring in a string.

If the substring is not contained in the string, the method returns -1.

To cover the scenario where the string contains a single word (no spaces), we check if the indexOf method returns -1, and if it does, we return an empty string.

If you don't want to remove the word if a string contains a single word, delete the if statement.
index.js
function removeFirstWord(str) { const indexOfSpace = str.indexOf(' '); return str.substring(indexOfSpace + 1); } console.log(removeFirstWord('Hello World')); // 👉️ World console.log(removeFirstWord('hello')); // 👉️ 'hello' console.log(removeFirstWord('one two three')); // 👉️ two three

The last step is to use the String.substring method to get a portion of the string without the first word.

The parameter we passed to the substring method is the start index - the index of the first character to be included in the new string.

We don't want to include the space in the new string, so we add 1 to the index of the space.

The String.substring method doesn't change the original string, it returns a new string. Strings are immutable in JavaScript.

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.