Borislav Hadzhiev
Last updated: Oct 11, 2021
Check out my new book
To replace the last occurrence of a character in a string:
lastIndexOf()
method to get the last index of the character.substring()
method twice, to get the parts of the string before
and after the character to be replaced.substring
method.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
.
0
and the last character str.length - 1
.The parameters we pass to the String.substring method are:
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.
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.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
.