EN
JavaScript - remove first n characters from string
17 points
In JavaScript it is possible to remove the first n characters from the string in the following way.
xxxxxxxxxx
1
// remove first n characters from string
2
function removeFirstChars(text, n) {
3
return text.slice(n);
4
}
5
6
console.log( removeFirstChars('12345', 0) ); // 12345
7
console.log( removeFirstChars('12345', 1) ); // 2345
8
console.log( removeFirstChars('12345', 2) ); // 345
9
console.log( removeFirstChars('12345', 3) ); // 34
10
console.log( removeFirstChars('12345', 4) ); // 5
11
12
// below results are empty, that's why we compare them to ''
13
console.log( removeFirstChars('12345', 5) === '' ); // true
Note:
We can achieve the same results using:
- String
substring()
method- String
replace()
method