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