EN
TypeScript - replace last n characters in string
0 points
In this article, we're going to have a look at how to replace the last n characters from string in TypeScript.
This approach allows getting substring by using negative indexes. So by using 0
and -n
indexes as the range we get <0, text.length - n>
text range. Then, we add the replacement
at the end of the result
string to replace the missing two characters.
xxxxxxxxxx
1
const text: string = 'ABCD';
2
const n: number = 3;
3
const replacement: string = 'xyz';
4
const result: string = text.slice(0, -n) + replacement;
5
6
console.log(result); // Axyz
Output:
xxxxxxxxxx
1
Axyz
This is an alternative approach to slice
method based solution. We remove the last n
characters to add the replacement
at the end of the result
string to replace the missing n
characters.
xxxxxxxxxx
1
const text: string = 'ABCD';
2
const n: number = 3;
3
const replacement: string = 'xyz';
4
const result: string = text.substring(0, text.length - n) + replacement;
5
6
console.log(result); // Axyz
Output:
xxxxxxxxxx
1
Axyz