EN
JavaScript - remove first 3 characters from string
9 points
In JavaScript it is possible to remove first 3 characters from string in following ways.
xxxxxxxxxx
1
var text = '12345';
2
var substring = text.slice(3);
3
4
console.log(substring); // 45
In second example we can see that we can also use string slice on empty or shorter string then 3 characters (or in case if we want to remove n characters from our string).
xxxxxxxxxx
1
// true means string is empty
2
console.log( ''.slice(3) === '' ); // empty
3
console.log( '1'.slice(3) === '' ); // empty
4
console.log( '12'.slice(3) === '' ); // empty
5
console.log( '123'.slice(3) === '' ); // empty
6
console.log( '1234'.slice(3) ); // 4
7
console.log( '12345'.slice(3) ); // 45
8
console.log( '123456'.slice(3) ); // 456
9
console.log( '1234567'.slice(3) ); // 4567
We use ''.slice(3) === ''
to see that the string after slice operation is empty.
Empty result means that string was shorter then 3 characters or the length was exactly 3 characters and our string is empty (the length of the string is 0).
Because string slice returns string then we can also call string length method to check the size of returned string, like on below example:
xxxxxxxxxx
1
console.log( ''.slice(3) === '' ); // empty
2
console.log( ''.slice(3).length ); // 0
xxxxxxxxxx
1
var text = '12345';
2
var substring = text.substring(3);
3
4
console.log(substring); // 45
xxxxxxxxxx
1
var text = '12345';
2
var substring = text.replace(/.{3}/, '');
3
4
console.log(substring); // 45