TypeScript - replace last 4 characters in string
In this article, we're going to have a look at how to replace the last 4 characters from string in TypeScript.
This approach allows getting substring by using negative indexes. So by using 0
and -4
indexes as the range we get <0, text.length - 4>
text range. Then, we add the replacement
at the end of the result
string to replace the missing four characters.
xxxxxxxxxx
const text: string = 'ABCDE';
const replacement: string = '1234';
const result: string = text.slice(0, -4) + replacement;
console.log(result); // A1234
Output:
xxxxxxxxxx
A1234
This is an alternative approach to slice
method based solution. We remove the last 4
characters to add the replacement
at the end of the result
string to replace the missing four characters.
xxxxxxxxxx
const text: string = 'ABCDE';
const replacement: string = '1234';
const result: string = text.substring(0, text.length - 4) + replacement;
console.log(result); // A1234
Output:
xxxxxxxxxx
A1234
There is another trick that allows replacing all characters that match expression conditions with an empty string. By using .{0,4}$
pattern we match any 4
characters (up to 4 characters) that are located at the end of the string. Then, we add the replacement
at the end of the result
string to replace the missing four characters.
xxxxxxxxxx
const text: string = 'ABCDE';
const replacement: string = '1234';
const result: string = text.replace(/.{0,4}$/, '') + replacement;
console.log(result); // A1234
Output:
xxxxxxxxxx
A1234