Languages
[Edit]
EN

JavaScript - remove prefix from string

0 points
Created by:
Admin Dirask Community
1420

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

Quick solution:

// ONLINE-RUNNER:browser;

let text = 'ABCD';

// replace "AB" only if it is at the beginning
let result1 = text.replace(/^(AB)/,'');

// remove the first two characters
let result2 = text.slice(2);

// remove the first two characters
let result3 = text.substring(2);


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

 

Practical examples

1. String.prototype.replace() with regex

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

// ONLINE-RUNNER:browser;

let text = 'ABCD';

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

console.log(result);  // CD

2. String.prototype.slice()

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

// ONLINE-RUNNER:browser;

let text = 'ABCD';

// remove the first two characters
let result = text.slice(2);

console.log(result);  // CD

3. String.prototype.substring()

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

// ONLINE-RUNNER:browser;

let text = 'ABCD';

// remove the first two characters
let result = text.substring(2);

console.log(result);  // CD

References

JavaScript - String (popular problems)

JavaScript - remove prefix from string
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