800

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.

nicael
  • 18,550
  • 13
  • 57
  • 90
Jings
  • 8,360
  • 3
  • 18
  • 17

17 Answers17

1294

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);
}
Max
  • 739
  • 2
  • 8
  • 23
Shaded
  • 17,276
  • 8
  • 37
  • 62
  • 12
    @Stephen: In this case, it wouldn't make a difference because `charAt` always returns a string, even if the index exceeds the index of the last character, so there's no type coercion performed, and the algorithm ends up being identical. But I do prefer `===` over `==` even when it doesn't make a difference. ;) – user113716 Oct 17 '11 at 21:32
  • 1
    @user113716 Wouldn't that exactly be the reason to use === so that javascript doesn't have to check if the types are the same? – Hejner Feb 11 '13 at 13:07
  • @Hejner: The performance difference is negligible on modern JS engines, so it's quite unnecessary. Depends on your preference. – Wk_of_Angmar Apr 08 '13 at 23:50
  • 5
    @Hejner: If the types are the same, as they always would be in this case, then `===` and `==` perform precisely the same steps (according to the spec, at least), so there is no reason to expect one to perform better than the other. – Tim Down Oct 28 '13 at 09:40
  • @TimDown actually not true, because you would have extra conditional logic for type checking. – Miguel Coder Jul 11 '18 at 01:38
  • 2
    @MiguelCoder. According to the spec, the steps are the same (browser implementations may differ, of course). Read it if you don't believe me. – Tim Down Jul 13 '18 at 09:12
  • While useful, your response does NOT do what was asked. The question asked for ONLY the first character to be removed.. your solution removes all similar characters at the beginning of a string. – Really Nice Code Mar 25 '19 at 18:27
  • 4
    @ReallyNiceCode putting aside the fact that the question was asked over 8 years ago. It was stated "The 0 can be there more than once." and the asker accepted my solution. – Shaded Mar 26 '19 at 13:41
  • 9
    Although still valid, you should update your reply, by replacing `substr` with `substring`. Check MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr – Soul Reaver Oct 26 '19 at 18:07
246

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.

jave.web
  • 13,880
  • 12
  • 91
  • 125
104

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 );
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
user113716
  • 318,772
  • 63
  • 451
  • 440
  • Works great. Plus, `.substr` is [deprecated](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr). – User 1058612 Apr 04 '22 at 16:40
  • const pathnameStandardized = pathname.charAt(0) === '/' ? pathname.slice(1) : pathname – justdvl Apr 14 '22 at 10:09
81

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/, "");
Tim Down
  • 318,141
  • 75
  • 454
  • 536
28

You can do it with substring method:

let a = "My test string";

a = a.substring(1);

console.log(a); // y test string
Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37
23

One simple solution is to use the Javascript slice() method, and pass 1 as a parameter

let str = "khattak01"
let resStr = str.slice(1)
console.log(resStr)

Result : hattak01

KillerKode
  • 957
  • 1
  • 12
  • 31
Khattak01
  • 365
  • 4
  • 10
22

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);
}
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
adarshr
  • 61,315
  • 23
  • 138
  • 167
11

const string = '0My string';
const result = string.substring(1);
console.log(result);

You can use the substring() javascript function.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Force Bolt
  • 1,117
  • 9
  • 9
9
var s = "0test";
if(s.substr(0,1) == "0") {
    s = s.substr(1);
}

For all 0s: http://jsfiddle.net/An4MY/

String.prototype.ltrim0 = function() {
 return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();
zsalzbank
  • 9,685
  • 1
  • 26
  • 39
  • Yeah, this would work, if only one 0 is in the string. But i need it also if the String looks like var s = "00test0"; then only the first two 0 had to be replaced – Jings Dec 30 '10 at 16:43
  • 1
    Why not `charAt`? Why the brackets? Why a prototype extension? Yuck. – Ry- Aug 07 '13 at 17:24
6
//---- remove first and last char of str    
str = str.substring(1,((keyw.length)-1));

//---- remove only first char    
str = str.substring(1,(keyw.length));

//---- remove only last char    
str = str.substring(0,(keyw.length));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
bambolobred
  • 61
  • 1
  • 1
4

try

s.replace(/^0/,'')

console.log("0string  =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
3

String.prototype.trimStartWhile = function(predicate) {
    if (typeof predicate !== "function") {
     return this;
    }
    let len = this.length;
    if (len === 0) {
        return this;
    }
    let s = this, i = 0;
    while (i < len && predicate(s[i])) {
     i++;
    }
    return s.substr(i)
}

let str = "0000000000ABC",
    r = str.trimStartWhile(c => c === '0');
    
console.log(r);
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
3

Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:

var cutOutZero = function(value) {
    if (value.length && value.length > 0 && value[0] === '0') {
        return value.substring(1);
    }

    return value;
};

http://jsfiddle.net/TRU66/1/

bdukes
  • 152,002
  • 23
  • 148
  • 175
1

Another alternative to get the first character after deleting it:

// Example string
let string = 'Example';

// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];

console.log(character);
// 'E'

console.log(string);
// 'xample'

Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36
1

Another alternative answer

str.replace(/^0+/, '')
Syscall
  • 19,327
  • 10
  • 37
  • 52
0

From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.

var str = "0000one two three0000"; //TEST  
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER

Original implementation for this on JS

string.trim():
if (!String.prototype.trim) {
 String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,'');
 }
}
fino
  • 3,764
  • 2
  • 23
  • 16
  • we don't consider confusion an implementation problem, however, it is often attributed to a capacity deficiency of keeping up with the variables your environment presents to you. In this case, your neural connections are incapable of handling the necessary understanding of this altered adoption of a native js function implementation as an answer to the original question. – fino May 08 '20 at 19:21
-1
var test = '0test';
test = test.replace(/0(.*)/, '$1');
kelloti
  • 8,705
  • 5
  • 46
  • 82