EN
JavaScript - 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 JavaScript.
Quick solution
xxxxxxxxxx
1
let text = 'ABCD';
2
let n = 3;
3
let result = 'xyz' + text.slice(n);
4
5
console.log(result); // xyzD
or:
xxxxxxxxxx
1
let text = 'ABCD';
2
let n = 3;
3
let replacer = 'xyz';
4
5
let result = 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
let text = 'ABCD';
2
let n = 3;
3
let replacer = 'xy';
4
5
let result = replacer + 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
.
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
let text = 'ABCD';
2
let n = 3;
3
let replacer = 'xy';
4
5
let result = 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
.