Replace Last Occurrence of Character in String in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
7 min

banner

# Table of Contents

  1. Replace the Last Occurrence of a Character in a String in Javascript
  2. Replace the Last Occurrence of a Character in String using split()
  3. Replace the Last Occurrence of a Character in String using substring()
  4. Remove the last Occurrence of a Character from a String in JS

# Replace the Last Occurrence of a Character in a String in Javascript

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. Use the slice() method twice to get the parts before and after the character.
  3. Add the replacement string between the two parts of the string.
index.js
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

replace last occurrence of character in string

The code for this article is available on GitHub
If you need to replace the last occurrence of a substring, use the replacement string's length to determine the start index in the second call to the slice() method.
index.js
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.

index.js
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:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring
index.js
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.

index.js
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().

index.js
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.

index.js
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.

index.js
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.

# Replace the Last Occurrence of a Character in String using split()

This is a three-step process:

  1. Use the lastIndexOf() method to get the last index of the character.
  2. Use the String.split() method to split the string into an array of characters.
  3. Replace the array element at the index.
index.js
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, '.'));

replace last occurrence of character in string using split

The code for this article is available on GitHub

We used the String.split() method to split the string into an array of characters.

index.js
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.

index.js
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.

# Replace the Last Occurrence of a Character in String using substring()

This is a three-step process:

  1. Use the lastIndexOf() method to get the last index of the character.
  2. Use the substring() method twice to get the parts before and after the character.
  3. Add the replacement string between the two parts of the string.
index.js
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

replace last occurrence of character in string using substring

The code for this article is available on GitHub

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:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe 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:

  • The 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.
index.js
const str = 'bobby'; console.log(str.substring(3, 0)); // ๐Ÿ‘‰๏ธ bob console.log(str.slice(3, 0)); // ๐Ÿ‘‰๏ธ ''
  • If either of both arguments passed to substring() are negative, they are treated as if they were 0.
index.js
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.

# Remove the last Occurrence of a Character from a String in JS

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

  1. Use the lastIndexOf() method to get the last index of the character.
  2. Use the slice() method twice to get the parts before and after the character.
  3. Concatenate the two parts of the string using the addition (+) operator.
index.js
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 code for this article is available on GitHub

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:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe 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.

index.js
const str = 'hello world'; const lastIndex = str.lastIndexOf('l'); console.log(str.slice(0, lastIndex)); // ๐Ÿ‘‰๏ธ hello wor console.log(str.slice(lastIndex + 1)); // ๐Ÿ‘‰๏ธ d
JavaScript indexes are zero-based, so the first character in a string has an index of 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.

# Remove the last occurrence of a substring from a 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.

index.js
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'));
The code for this article is available on GitHub

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:

index.js
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev