Languages
[Edit]
EN

TypeScript - replace first 3 characters in string

0 points
Created by:
Mahir-Bright
1311

In this article, we would like to show you how to replace the first 3 characters in string in TypeScript.

Quick solution

const text: string = 'ABCD';
const result: string = 'xyz' + text.slice(3);

console.log(result); // xyzD

or:

const text: string = 'ABCD';
const replacer: string = 'xyz';

const result: string = replacer.concat(text.slice(3));

console.log(result); // xyzD

or:

const text: string = 'ABCD';
const result: string = text.replace(/^.{3}/g, 'xyz');

console.log(result); // xyzD

 

1. Using string slice() with + operator

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:

const text: string = 'ABCD';
const replacer: string = 'xy';

const result: string = replacer + text.slice(3);

console.log(result); // xyD

Output:

xyD

Note:

The replacer for the three removed characters may cosist of any number of characters, not exactly 3.

2. Using string slice() with concat() method

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:

const text: string = 'ABCD';
const replacer: string = 'xy';

const result: string = replacer.concat(text.slice(3));

console.log(result); // xyD

Output:

xyD

Note:

The replacer for the two removed characters may cosist of any number of characters, not exactly 3.

3. Using string replace() with regex

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:

const text: string = 'ABCD';
const result: string = text.replace(/^.{3}/g, 'xyz');

console.log(result); // xyzD

Output:

xyzD
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join