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:
xxxxxxxxxx
1
const text = 'ABCD';
2
3
const result1 = text.slice(2); // omits the first two characters
4
const result2 = text.substring(2); // omits the first two characters
5
const result3 = text.replace(/^AB/, ''); // replaces "AB" only if text starts with it
6
7
console.log(result1); // CD
8
console.log(result2); // CD
9
console.log(result3); // CD
In this example, we use String
slice()
method to omit the first two letters from the text
.
xxxxxxxxxx
1
const text = 'ABCD';
2
const result = text.slice(2);
3
4
console.log(result); // CD
In this example, we use String
substring()
method to omit the first two letters from the text
.
xxxxxxxxxx
1
const text = 'ABCD';
2
const result = text.substring(2);
3
4
console.log(result); // CD
In this example, we use String
replace()
method with a regular expression to replace the first two letters (AB
) with an empty string.
xxxxxxxxxx
1
const text = 'ABCD';
2
const result = text.replace(/^AB/, '');
3
4
console.log(result); // CD