HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Delete first character of string if it is 0

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringcharacterdeletefirst

Problem

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.

Solution

You can remove the first character of a string using substring:

var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"


To remove all 0's at the start of the string:

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

Code Snippets

var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
var s = "0000test";
while(s.charAt(0) === '0')
{
 s = s.substring(1);
}

Context

Stack Overflow Q#4564414, score: 1359

Revisions (0)

No revisions yet.