Remove the First Word from a String in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

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 to remove the last word from a string.

The first thing we did is use 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 that 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(' '); // ๐Ÿ‘‡๏ธ if you want to keep single words, delete this // if (indexOfSpace === -1) { // return ''; // } 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 final 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 at which we start extraction of characters.

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

The function returns a new string, omitting the first word and the space of the provided string.

Further Reading #

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