EN
TypeScript - replace first n characters in string
0 points
In this article, we would like to show you how to replace the first n characters in string in TypeScript.
Quick solution
xxxxxxxxxx
1
const text: string = 'ABCD';
2
const n: number = 3;
3
const result: string = 'xyz' + text.slice(n);
4
5
console.log(result); // xyzD
or:
xxxxxxxxxx
1
const text: string = 'ABCD';
2
const n: number = 3;
3
const replacer: string = 'xyz';
4
5
const result: string = replacer.concat(text.slice(n));
6
7
console.log(result); // xyzD
In this example, we use string slice()
method to remove the first n
characters of the text
string. Then with +
operator we add the remainder of the text
to the replacer
.
Runnable example:
xxxxxxxxxx
1
// ONLINE-RUNNER:browser;
2
3
const text: string = 'ABCD';
4
const n: number = 3;
5
const replacer: string = 'xy';
6
7
const result: string = replacer + text.slice(n);
8
9
console.log(result); // xyD
Output:
xxxxxxxxxx
1
xyD
Note:
The
replacer
for then
removed characters may cosist of any number of characters, not exactlyn
.
In this example, we use string slice()
method to remove the first n
characters of the text
string. Then with concat()
method we add the remainder of the text
to the replacer
.
Runnable example:
xxxxxxxxxx
1
const text: string = 'ABCD';
2
const n: number = 3;
3
const replacer: string = 'xy';
4
5
const result: string = replacer.concat(text.slice(n));
6
7
console.log(result); // xyD
Note:
The
replacer
for then
removed characters may cosist of any number of characters, not exactlyn
.
Output:
xxxxxxxxxx
1
xyD