EN
JavaScript - remove prefix from string
3
points
In this article, we would like to show you how to remove prefix from string in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const text = 'ABCD';
const result1 = text.slice(2); // omits the first two characters
const result2 = text.substring(2); // omits the first two characters
const result3 = text.replace(/^AB/, ''); // replaces "AB" only if text starts with it
console.log(result1); // CD
console.log(result2); // CD
console.log(result3); // CD
Practical examples
1. String
slice()
In this example, we use String
slice()
method to omit the first two letters from the text
.
// ONLINE-RUNNER:browser;
const text = 'ABCD';
const result = text.slice(2);
console.log(result); // CD
2. String
substring()
In this example, we use String
substring()
method to omit the first two letters from the text
.
// ONLINE-RUNNER:browser;
const text = 'ABCD';
const result = text.substring(2);
console.log(result); // CD
3. String
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.
// ONLINE-RUNNER:browser;
const text = 'ABCD';
const result = text.replace(/^AB/, '');
console.log(result); // CD