Remove the Last 2 Words from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Jonathan Klok

Remove the Last 2 Words from a String #

To remove the last 2 words from a string:

  1. Call the split() method on the string to split it into an array of words.
  2. Use the slice method to get an array excluding the last 2 words of the string.
  3. Call the join() method on the array and join the words with a space.
index.js
const str = 'one two three four'; const withoutLast2Words = str.split(' ').slice(0, -2).join(' '); console.log(withoutLast2Words); // ๐Ÿ‘‰๏ธ 'one two'

The first thing we did is use the String.split method to split the string into an array of substrings.

index.js
const str = 'one two three four'; // ๐Ÿ‘‡๏ธ๏ธ ['one', 'two', 'three', 'four'] console.log(str.split(' '));

The next step is to use the Array.slice method to get a portion of the array without the last 2 elements (words).

We passed the following parameters to the slice method:

  1. start index - the index (zero-based) of the first element to be included in the new array
  2. end index - extract elements up to, but not including this index. A negative index of -2 means go up to, but not including the last 2 elements of the array
Passing an end index parameter of -2 and array.length - 2 is the same. We instruct the slice method to go up to, but not including the last 2 elements of the array.
index.js
const str = 'one two three four'; console.log(str.split(' ').slice(0, -2)); // ๐Ÿ‘‰๏ธ ['one', 'two']

The last step is to use the Array.join method to join the words back into a string.

The only parameter the join method takes is a separator, for which we provide a space.

The result is a new string that doesn't contain the last 2 words from the original string.

index.js
const str = 'one two three four'; const withoutLast2Words = str.split(' ').slice(0, -2).join(' '); console.log(withoutLast2Words); // ๐Ÿ‘‰๏ธ 'one two'

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