TypeScript - replace first 2 characters in string
In this article, we would like to show you how to replace the first 2 characters in a string in TypeScript.
Quick solution
xxxxxxxxxx
const text: string = 'ABCD';
const result: string = 'xy' + text.slice(2);
console.log(result); // xyCD
or:
xxxxxxxxxx
const text: string = 'ABCD';
const replacer: string = 'xy';
const result: string = replacer.concat(text.slice(2));
console.log(result); // xyCD
or:
xxxxxxxxxx
const text: string = 'ABCD';
const result: string = text.replace(/^.{2}/g, 'xy');
console.log(result); // xyCD
In this example, we use string slice()
method to remove the first 2 characters of the text
string. Then with +
operator we add the remainder of the text
to the replacer
.
Runnable example:
xxxxxxxxxx
const text: string = 'ABCD';
const replacer: string = 'xyz';
const result: string = replacer + text.slice(2);
console.log(result); // xyzCD
Output:
xxxxxxxxxx
xyzCD
Note:
The
replacer
for the two removed characters may cosist of any number of characters, not only 2.
In this example, we use string slice()
method to remove the first 2 characters of the text
string. Then with concat()
method we add the remainder of the text
to the replacer
.
Runnable example:
xxxxxxxxxx
const text: string = 'ABCD';
const replacer: string = 'xyz';
const result: string = replacer.concat(text.slice(2));
console.log(result); // xyzCD
Output:
xxxxxxxxxx
xyzCD
Note:
The
replacer
for the two removed characters may cosist of any number of characters, not only 2.
In this example, we use string replace()
with /^.{2}/g
regex to replace the first 2 characters in the text
string.
Regex explanation:
^
- matches the beginning of the string,.
- matches any character except linebreaks,{2}
- matches the specified quantity of the previous token (in our case the.
).
Runnable example:
xxxxxxxxxx
const text: string = 'ABCD';
const result: string = text.replace(/^.{2}/g, 'xyz');
console.log(result); // xyzCD
Output:
xxxxxxxxxx
xyzCD