Last updated: Mar 1, 2024
Reading timeยท7 min
To replace the last occurrence of a character in a string:
lastIndexOf()
method to get the last index of the character.slice()
method twice to get the parts before and after the
character.const str = 'bobbyhadz.com'; const lastIndex = str.lastIndexOf('b'); const replacement = '.'; const replaced = str.slice(0, lastIndex) + replacement + str.slice(lastIndex + 1); console.log(replaced); // ๐๏ธ bob.yhadz.com
slice()
method.const str = 'bbobbyhadz.com'; const lastIndex = str.lastIndexOf('bb'); const replacement = '..'; const replaced = str.slice(0, lastIndex) + replacement + str.slice(lastIndex + replacement.length); console.log(replaced); // ๐๏ธ bbo..yhadz.com
The String.lastIndexOf() method returns the index of the last occurrence of a substring in a string.
const str = 'bobbyhadz.com'; const lastIndex = str.lastIndexOf('b'); console.log(lastIndex); // ๐๏ธ 3
The method returns -1
if the substring is not contained in the string.
We used the String.slice()
method to get the parts of the string before and
after the character that is to be replaced.
The String.slice() method extracts a section of a string and returns it, without modifying the original string.
The String.slice()
method takes the following arguments:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
const str = 'bobbyhadz.com'; const lastIndex = str.lastIndexOf('b'); console.log(lastIndex); // ๐๏ธ 3 // ๐๏ธ bob console.log(str.slice(0, lastIndex)); // ๐๏ธ yhadz.com console.log(str.slice(lastIndex + 1));
When only a single argument is passed to the String.slice()
method, the slice
goes to the end of the string.
We added 1
to the start index in the second call to the str.slice()
method
to omit the character to be replaced from the result.
You can also use this approach if you need to replace the last occurrence of a single character with multiple characters.
const str = 'bobbyhadz.com'; const lastIndex = str.lastIndexOf('b'); const replacement = '...'; const replaced = str.slice(0, lastIndex) + replacement + str.slice(lastIndex + 1); console.log(replaced); // ๐๏ธ bob...yhadz.com
The code sample replaces the last occurrence of b
with multiple characters.
If you need to replace the last occurrence of multiple characters with multiple
characters, use the replacement string's length to determine the start index in
the second call to String.slice()
.
const str = 'bbobbyhadz.com'; const lastIndex = str.lastIndexOf('bb'); const replacement = '..'; const replaced = str.slice(0, lastIndex) + replacement + str.slice(lastIndex + replacement.length); console.log(replaced); // ๐๏ธ bbo..yhadz.com
We practically skip exactly as many characters as there are in the replacement string.
If you have to replace the last occurrence of a character often, create a reusable function.
function replaceLastOccurrence(string, replacement) { const lastIndex = str.lastIndexOf('b'); const replaced = string.slice(0, lastIndex) + replacement + string.slice(lastIndex + replacement.length); return replaced; } const str = 'bobbyhadz.com'; // ๐๏ธ bob.yhadz.com console.log(replaceLastOccurrence(str, '.'));
The function takes the string and the replacement string as parameters and replaces the last occurrence of the substring in the string.
The indexOf
method returns -1
if the string doesn't 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.slice(0, lastIndex) + replacement + str.slice(lastIndex + 1); } console.log(replaced); // ๐๏ธ Hello Wor.d
We check if the lastIndex
variable is not equal to -1
before we replace the
last occurrence of the character.
Notice that we declared the replaced
variable using the let
keyword, so we
can reassign it in our if
statement.
We want the replaced
variable to be accessible outside the if
block, so we
declared it outside.
The replaced
variable would only store a string if the call to the
lastIndexOf()
method doesn't return -1
.
Alternatively, you can use the String.split()
method.
This is a three-step process:
lastIndexOf()
method to get the last index of the character.String.split()
method to split the string into an array of
characters.function replaceLastOccurrence(string, replacement) { const lastIndex = str.lastIndexOf('b'); const arr = string.split(''); console.log(arr); arr[lastIndex] = replacement; return arr.join(''); } const str = 'bobbyhadz.com'; // ๐๏ธ bob.yhadz.com console.log(replaceLastOccurrence(str, '.'));
We used the String.split()
method to split the string into an array of
characters.
const str = 'bobbyhadz.com'; // [ // 'b', 'o', 'b', 'b', // 'y', 'h', 'a', 'd', // 'z', '.', 'c', 'o', // 'm' // ] console.log(str.split(''));
We used the lastIndexOf()
method to get the last index of the character in the
string and
replaced the array element at that
index.
The last step is to use the Array.join()
method to join the array into a
string.
const str = 'bobbyhadz.com'; const arr = str.split(''); arr[3] = '.'; const result = arr.join(''); // ๐๏ธ bob.yhadz.com console.log(result);
You can also use the String.substring()
method to replace the last occurrence
of a character in a string.
This is a three-step process:
lastIndexOf()
method to get the last index of the character.substring()
method twice to get the parts before and after the
character.const str = 'bobbyhadz.com'; const lastIndex = str.lastIndexOf('b'); const replacement = '.'; const replaced = str.substring(0, lastIndex) + replacement + str.substring(lastIndex + 1); console.log(replaced); // ๐๏ธ bob.yhadz.com
The String.substring() method returns a slice of the string from the start index to the excluding end index.
The method takes the following parameters:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
If no end
index is specified the slice goes to the end of the string.
We used the String.substring()
method in a similar way to how we used the
String.slice()
method.
However, there are a couple of
differences
between the String.substring()
and the String.slice()
methods:
substring()
method swaps its start and end index if the start index is
greater than the end index. The slice()
method returns an empty string in
this case.const str = 'bobby'; console.log(str.substring(3, 0)); // ๐๏ธ bob console.log(str.slice(3, 0)); // ๐๏ธ ''
substring()
are negative, they are
treated as if they were 0
.const str = 'bobby'; console.log(str.substring(-3)); // ๐๏ธ bobby console.log(str.slice(-3)); // ๐๏ธ bby
When given a negative index, the slice()
method counts backward from the end
of the string to find the indexes.
To remove the last occurrence of a character from a string:
lastIndexOf()
method to get the last index of the character.slice()
method twice to get the parts before and after the
character.function removeLastOccurrence(string, char) { const lastIndex = string.lastIndexOf(char); return string.slice(0, lastIndex) + str.slice(lastIndex + 1); } const str = 'hello world'; // ๐๏ธ hello word console.log(removeLastOccurrence(str, 'l')); // ๐๏ธ hello wrld console.log(removeLastOccurrence(str, 'o'));
The String.lastIndexOf() method returns the index of the last occurrence of a substring in a string.
The method returns -1
if the substring is not contained in the string.
Once we have the last index of the character in the string, we get the 2 substrings containing the rest of the string, excluding the character at the specific index.
The String.slice() method extracts a section of a string and returns it, without modifying the original string.
The String.slice()
method takes the following arguments:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
When only a single argument is passed to the String.slice()
method, the slice
goes to the end of the string.
In our first call to the slice()
method, we went from the character at index
0
, up to, but not including the index of the last occurrence of the character.
const str = 'hello world'; const lastIndex = str.lastIndexOf('l'); console.log(str.slice(0, lastIndex)); // ๐๏ธ hello wor console.log(str.slice(lastIndex + 1)); // ๐๏ธ d
0
, and the last character has an index of 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.
This approach can be used to remove the last occurrence of a substring from a string, it doesn't have to be a single character.
function removeLastOccurrence(string, substring) { const lastIndex = string.lastIndexOf(substring); return string.slice(0, lastIndex) + str.slice(lastIndex + substring.length); } const str = 'abc 123 abc 123'; // ๐๏ธ 'abc 123 123' console.dir(removeLastOccurrence(str, 'abc'));
Instead of adding 1 to the last index, we used the substring's length to determine where to start extraction.
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:
function removeLastOccurrence(string, substring) { const lastIndex = string.lastIndexOf(substring); if (lastIndex !== -1) { return string.slice(0, lastIndex) + str.slice(lastIndex + substring.length); } return string; } const str = 'abc 123 abc 123'; // ๐๏ธ 'abc 123 123' console.dir(removeLastOccurrence(str, 'abc')); // ๐๏ธ 'abc 123 abc 123' console.dir(removeLastOccurrence(str, 'XYZ'));
We used an if
statement to check if the lastIndexOf()
method didn't return
-1
before removing the last occurrence of the substring from the string.
If the method returned -1
, then the substring is not contained in the string,
so we return the string as is.
You can learn more about the related topics by checking out the following tutorials: