JavaScript strings are immutable, it can’t remove characters from them but can carte new strings with changes. There are 2 ways to remove the first character from the string in JavaScript.
substring()
method
This method returns the part of the string between the specified indexes or to the end of the string
str.substring(1);
slice()
method
This method extracts the text from a string and returns a new string.
str.slice(1);
Remove the first character from the string JavaScript
Simple example code.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
let str = 'Hello';
// substring
var res1 = str.substring(1);
console.log(res1);
//slice
var res2 = str.slice(1);
console.log(res2);
</script>
</body>
</html>
Output:
Delete the first character of string if it is 0
To remove all 0’s at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
console.log(s);
The easiest way to strip all leading 0
s is:
var s = "00test";
s = s.replace(/^0+/, "");
If it just stripping a single leading 0
character, as the question implies, you could use
s = s.replace(/^0/, "");
Do comment if you have any doubts or suggestions on this Js remove char code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version