Replace Last Occurrence of Character in String in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 11 20212 min read

banner

Photo by Ethan Hoover

Replace the Last Occurrence of a Character in String #

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

  1. Use the lastIndexOf() method to get the last index of the character.
  2. Call the substring() method twice, to get the parts of the string before and after the character to be replaced.
  3. Add the replacement character between the two calls to the substring method.
index.js
const str = 'Hello World'; // ๐Ÿ‘‡๏ธ 9 const lastIndex = str.lastIndexOf('l'); const replacement = '.'; const replaced = str.substring(0, lastIndex) + replacement + str.substring(lastIndex + 1); console.log(replaced); // ๐Ÿ‘‰๏ธ Hello Wor.d

We first use the String.lastIndexOf method to get the last index of the l character in the string Hello World.

Indexes are zero-based in JavaScript. The index of the first character in a string is 0 and the last character str.length - 1.

The parameters we pass to the String.substring method are:

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

Our first call to the substring method gets us the string from the first character up to, but not including the character we want to replace.

We then add the replacement character to the string.

The last step is to get the rest of the string. However, we don't want to include the character we already replaced, so we increment the start index parameter by 1.

Note that the substring method does not change the contents of the original string, it returns a new string containing a part of the original string.

The indexOf method returns -1 if the string does not contain the provided character. If this is a possible scenario in your application, check for it in an if statement to avoid possible bugs.
index.js
const str = 'Hello World'; // ๐Ÿ‘‡๏ธ 9 const lastIndex = str.lastIndexOf('l'); const replacement = '.'; let replaced; if (lastIndex !== -1) { replaced = str.substring(0, lastIndex) + replacement + str.substring(lastIndex + 1); } console.log(replaced); // ๐Ÿ‘‰๏ธ Hello Wor.d

In the code snippet we check if the lastIndex variable is not equal to -1, before we replace the last occurrence of the character.

Notice that we declare the replaced variable using the let keyword, so we can reassign it in our if statement.

We want the replace variable to be accessible outside the if block, so we declare it outside.

The replaced variable would only hold a string, if the call to the lastIndexOf method didn't return -1.

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