Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
Jings Avatar asked Dec 30 '10 16:12

Jings


4 Answers

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.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.

like image 24
jave.web Avatar answered Oct 18 '22 18:10

jave.web


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);
}
like image 194
Shaded Avatar answered Oct 18 '22 17:10

Shaded


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 );
like image 40
user113716 Avatar answered Oct 18 '22 18:10

user113716


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/, "");
like image 40
Tim Down Avatar answered Oct 18 '22 17:10

Tim Down