Languages
[Edit]
EN

TypeScript - remove prefix from string

0 points
Created by:
Mariam-Barron
841

In this article, we would like to show you how to remove prefix from string in TypeScript.

Quick solution:

const text: string = 'ABCD';

const result1: string = text.replace(/^(AB)/, ''); // replaces "AB" only if it is at the beginning
const result2: string = text.slice(2);             // removes the first two characters
const result3: string = text.substring(2);         // removes the first two characters

console.log(result1); // CD
console.log(result2); // CD
console.log(result3); // CD

 

Practical examples

1. String.prototype.replace() with regular expression

In this example, we use String replace() method with a regular expression to replace the first two letters (AB) with an empty string.

const text: string = 'ABCD';

// replace the AB only at the beginning of the string
const result: string = text.replace(/^(AB)/, '');

console.log(result); // CD

Output:

CD

2. String.prototype.slice()

In this example, we use String slice() method to remove the first two letters from the text.

const text: string = 'ABCD';

// remove the first two characters
const result: string = text.slice(2);

console.log(result); // CD

Output:

CD

3. String.prototype.substring()

In this example, we use String substring() method to remove the first two letters from the text.

const text: string = 'ABCD';

// remove the first two characters
const result: string = text.substring(2);

console.log(result); // CD

Output:

CD
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