Borislav Hadzhiev
Mon Oct 11 2021·3 min read
Photo by Kym MacKinnon
To replace the last character in a string:
slice()
method, passing it a start index of 0
and an end index
of -1
to get a string, containing the characters up to the last one.+
operator to append the replacement character to the string.const str = 'Hello World.'; const replaced = str.slice(0, -1) + '!'; console.log(replaced); // 👉️ Hello World!
0
and the last an index of str.length - 1
.The parameters we pass to the String.slice method are:
-1
and str.length - 1
is the same. We instruct the slice
method to go up to, but not including the last character in the string.By getting a part of the string up to, but not including the last character, we are able to replace it with one or more characters.
This approach also works if we need to replace the last character with multiple characters.
const str = 'Hello World.'; const replaced = str.slice(0, -1) + '!!!'; console.log(replaced); // 👉️ Hello World!!!
Note that the slice
method does not change the contents of the original
string, it returns a new string containing a part of the original string.
An alternative, but also very common approach is to use the String.replace method.
To replace the last character in a string:
replace()
method, passing it a regular expression that matches the
last character in the string and the replacement character as parameters.replace
method will return a new string with the last character
replaced.const str = 'Hello World.'; const replaced = str.replace(/.$/, '!'); console.log(replaced); // 👉️ Hello World!
The parameters we passed to the replace
method are:
If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.
The .
character in our regular expression matches any single character.
The $
character matches the end of a string.
This satisfies our requirement to match and replace the last character in the string.
replace
method does not mutate the original string, it returns a new string. Strings are immutable in JavaScript.I prefer the first approach over using the replace
method because many
developers are not familiar with regular expressions.