Delete first character of a string in Javascript

Delete first character of a string in Javascript

I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.
Is there a simple function that checks the first character and deletes it if it is 0?
Right now, I’m trying it with the JS slice() function but it is very awkward.

Solutions/Answers:

Solution 1:

var s = "0000test";
while(s.charAt(0) === '0')
{
 s = s.substr(1);
}

This will kill any 0’s at the start of the string.

Solution 2:

Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don’t even need to call .length()

TL;DR : Remove first character from the string:

str = str.substring(1);

…yes it is that simple…

Removing some particular character(s):

As @Shaded suggested, just loop this while first character of your string is the “unwanted” character…

var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substr(1);
//yourString now contains "test"

.slice() vs .substring() vs .substr()

Quote from (and more on that in) What is the difference between String.slice and String.substring?

He also points out that if the parameters to slice are negative, they
reference the string from the end. Substring and substr doesn´t.

Solution 3:

Use .charAt() and .slice().

Example: http://jsfiddle.net/kCpNQ/

var myString = "0String";

if( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

If there could be several 0 characters at the beginning, you can change the if() to a while().

Example: http://jsfiddle.net/kCpNQ/1/

var myString = "0000String";

while( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

Solution 4:

The easiest way to strip all leading 0s is:

var s = "00test";
s = s.replace(/^0+/, "");

If just stripping a single leading 0 character, as the question implies, you could use

s = s.replace(/^0/, "");

Solution 5:

You can do it with substring method:

let a = "My test string";

a = a.substring(1);

console.log(a); // y test string

Solution 6:

Did you try the substring function?

string = string.indexOf(0) == '0' ? string.substring(1) : string;

Here’s a reference – https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

And you can always do this for multiple 0s:

while(string.indexOf(0) == '0')
{
    string = string.substring(1);
}