Remove first character from a string in JavaScript
This post will discuss how to remove the first character from a string in JavaScript.
Since strings are immutable in JavaScript, we can’t in-place remove characters from it. The idea is to create a new string instead. There are three ways in JavaScript to remove the first character from a string:
1. Using substring() method
The substring() method returns the part of the string between the specified indexes or to the end of the string.
|
1 2 3 4 5 6 7 8 |
let str = 'Hello'; str = str.substring(1); console.log(str); /* Output: ello */ |
You can easily extend the solution to remove the first n characters from the string.
|
1 2 3 4 5 6 7 8 9 |
let str = 'Hello'; let n = 3; str = str.substring(n); console.log(str); /* Output: lo */ |
2. Using slice() method
The slice() method extracts the text from a string and returns a new string.
|
1 2 3 4 5 6 7 8 |
let str = 'Hello'; str = str.slice(1); console.log(str); /* Output: ello */ |
This can be easily extended to remove first n characters from the string.
|
1 2 3 4 5 6 7 8 9 |
let str = 'Hello'; let n = 3; str = str.slice(n); console.log(str); /* Output: lo */ |
3. Using substr() method
The substr() method returns a portion of the string, starting at the specified index and extending for a given number of characters or until the string’s end.
|
1 2 3 4 5 6 7 8 |
let str = 'Hello'; str = str.substr(1); console.log(str); /* Output: ello */ |
Note that substr() might get deprecated in the future and should be avoided.
That’s all about removing the first character from a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)