TypeScript - replace first character in string
In this article, we would like to show you how to replace the first character in string in TypeScript.
Quick solution
xxxxxxxxxx
const text: string = 'ABC';
const result: string = 'x' + text.slice(1);
console.log(result); // xBC
or:
xxxxxxxxxx
const text: string = 'ABC';
const replacer: string = 'x';
const result: string = replacer.concat(text.slice(1));
console.log(result); // xBC
or:
xxxxxxxxxx
const text = 'ABC';
const result = text.replace(/^./g, 'x');
console.log(result); // xBC
In this example, we use string slice()
method to remove the first character of the text
string. Then with +
operator we add the remainder of the text
to the replacer
.
Runnable example:
xxxxxxxxxx
const text: string = 'ABC';
const replacer: string = 'x';
const result: string = replacer + text.slice(1);
console.log(result); // xBC
Output:
xxxxxxxxxx
xBC
Note:
The
replacer
for the removed character may cosist of any number of characters, not exactly one.
In this example, we use string slice()
method to remove the first character of the text
string. Then with concat()
method we add the remainder of the text
to the replacer
.
Runnable example:
xxxxxxxxxx
const text: string = 'ABC';
const replacer: string = 'x';
const result: string = replacer.concat(text.slice(1));
console.log(result); // xBC
Output:
xxxxxxxxxx
xBC
Note:
The
replacer
for the removed character may cosist of any number of characters, not exactly one.
In this example, we use string replace()
with /^./g
regex to replace the first character in the text
string.
Regex explanation:
^
- matches the beginning of the string,.
- matches any character except linebreaks.
Runnable example:
xxxxxxxxxx
const text: string = 'ABC';
const result: string = text.replace(/^./g, 'x');
console.log(result); // xBC
Output:
xxxxxxxxxx
xBC