Sometimes we need to remove the first character of a string with JavaScript.
In this article, we’ll look at how to remove the first character of a string with JavaScript.
String.prototype.substring
We can use the JavaScript string’s substring
method to extract a substring from a string.
We pass in the start and end index arguments respectively.
The character at the start index is included, but the character at the end index isn’t.
The end index is optional.
If we don’t include it, then the end index is the length
property value of the string.
For instance, we can write:
const str = "foobar";
const newStr = str.substring(1);
console.log(newStr)
Then newStr
is 'oobar'
.
String.prototype.slice
The JavaScript string’s slice
method also lets us get a substring from a string.
It takes the same arguments and they’re used the same way as substring
.
For instance, we can write:
const str = "foobar";
const newStr = str.slice(1);
console.log(newStr)
And we get the same result.
slice
also takes negative indexes.
Index -1 is the index of the last character of a string, -2 is the index of the 2nd last character of a string, and so on.
So to call slice
with negative indexes to extract the substring from the first character to the end of the string, we write:
const str = "foobar";
const newStr = str.slice(-str.length + 1);
console.log(newStr)
We multiply str.length
by -1 and add 1 to that to get the index of the 2nd character of the string.
And so newStr
is the same as the other examples.
Rest Operator
Since JavaScript strings are iterable objects, we can use the rest operator to get the characters other than the first in its own array.
For instance, we can write:
const str = "foobar";
const [firstChar, ...chars] = str
const newStr = chars.join('')
console.log(newStr)
We have the chars
array which has an array of characters from str
other than the first character.
Then we can call join
with an empty string to join the characters back into a string.
And so newStr
is the same as we have before.
Conclusion
We can use the substring
and slice
methods to extract a substring from a string that has the 2nd character to the end of the original string.
Also, we can use the rest operator to get all the characters other than the first characters and call join
to join the characters back into a string.