EN
JavaScript - replace last character in string
3
points
In this article, we're going to have a look at how to replace the last character from the string in JavaScript.
1. String slice()
method example
This approach allows getting substring by using negative indexes. So by using 0
and -1
indexes as the range we get <0, text.length - 1>
text range. Then, we add the replacement
at the end of the result
string to replace the missing character.
// ONLINE-RUNNER:browser;
let text = 'ABC';
let replacement = 'x';
let result = text.slice(0, -1) + replacement;
console.log(result); // ABx
2. String substring()
method example
This is an alternative approach to slice
method based solution. We remove the last character to add the replacement
at the end of the result
string to replace the missing character.
// ONLINE-RUNNER:browser;
let text = 'ABC';
let replacement = 'x';
let result = text.substring(0, text.length - 1) + replacement;
console.log(result); // ABx
3. String replace()
method example
There is another trick that allows replacing all characters that match expression conditions with an empty string. By using .$
pattern we match any character that is located at the end of the string.
// ONLINE-RUNNER:browser;
let text = 'ABC';
let replacement = 'x';
let result = text.replace(/.$/, replacement);
console.log(result); // ABx