Remove Last Occurrence of a Character in a String in JS

avatar

Borislav Hadzhiev

Last updated: Oct 26, 2021

banner

Photo from Unsplash

Remove Last Occurrence of a Character in a String #

To remove the last occurrence of a character in a string:

  1. Use the lastIndexOf() method to get the index of the last occurrence of the character.
  2. Concatenate the results from 2 calls to the slice method, excluding the character at the specific index.
index.js
const str = 'hello world'; const lastIndexOfL = str.lastIndexOf('l'); console.log(lastIndexOfL); // 👉️ 9 const removeLastL = str.slice(0, lastIndexOfL) + str.slice(lastIndexOfL + 1); console.log(removeLastL); // 👉️ hello word

In this example, we removed the last occurrence of the l character in the string hello world.

We used the String.lastIndexOf method to get the index of the last occurrence of the character in the string.

The lastIndexOf method returns -1 if the character is not found in the string.

The next step is to get 2 substrings containing the rest of the string, excluding the character at the specific index.

We passed the following 2 parameters to the String.slice method:

  1. the start index - the index of the first character to be included in the new string.
  2. the end index - go up to, but not including this character.

The slice method returns a new string containing a portion of the original string.

In our first call to the method, we went from the character at index 0, up to, but not including the index of the last occurrence of the character.

Indexes are zero-based in JavaScript, meaning the first character in a string has an index of 0, and the last - string.length - 1.

In our second call to the slice method, we added 1 to the last index of the character because we don't want it to be included in the new string.

A very important thing to note is that the lastIndexOf method returns -1 if the character is not found in the string.

To handle this scenario, you can use an if statement:

index.js
const str = 'hello world'; const lastIndexOfL = str.lastIndexOf('l'); console.log(lastIndexOfL); // 👉️ 9 let removeLastL = str; if (lastIndexOfL !== -1) { console.log('✅ character exists in string'); removeLastL = str.slice(0, lastIndexOfL) + str.slice(lastIndexOfL + 1); } else { console.log('⛔️ character does not exist in string'); }

We declared the removeLastL variable and set it to the string itself.

Before we use the slice method, we check if the lastIndexOf method found at least one match of the l character in the string.

If it did, we change the value of the removeLastL variable.

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.