Borislav Hadzhiev
Fri Oct 22 2021·2 min read
Photo by Benjamin Combs
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.
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
statement.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.