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.
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()
...
str = str.substring(1);
...yes it is that simple...
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.substring(1);
//yourString now contains "test"
.slice()
vs .substring()
vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr()
to be safe in modern world :)
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.
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);
}
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 );
The easiest way to strip all leading 0
s 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/, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With