Delete first character of string if it is 0

JavascriptString

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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);
}

Solution 2 - Javascript

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) https://stackoverflow.com/questions/2243824/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 - Javascript

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

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

You can do it with substring method:

let a = "My test string";

a = a.substring(1);

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

Solution 6 - Javascript

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);
}

Solution 7 - Javascript

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

Solution 8 - Javascript

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();

Solution 9 - Javascript

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

You can use the substring() javascript function.

Solution 10 - Javascript

//---- 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));

Solution 11 - Javascript

try

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

console.log("0string  =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );

Solution 12 - Javascript

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);

Solution 13 - Javascript

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/

Solution 14 - Javascript

var test = '0test';
test = test.replace(/0(.*)/, '$1');

Solution 15 - Javascript

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,'');
 }
}

Solution 16 - Javascript

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJingsView Question on Stackoverflow
Solution 1 - JavascriptShadedView Answer on Stackoverflow
Solution 2 - Javascriptjave.webView Answer on Stackoverflow
Solution 3 - Javascriptuser113716View Answer on Stackoverflow
Solution 4 - JavascriptTim DownView Answer on Stackoverflow
Solution 5 - JavascriptAndrewView Answer on Stackoverflow
Solution 6 - JavascriptadarshrView Answer on Stackoverflow
Solution 7 - JavascriptKhattak01View Answer on Stackoverflow
Solution 8 - JavascriptzsalzbankView Answer on Stackoverflow
Solution 9 - JavascriptForce BoltView Answer on Stackoverflow
Solution 10 - JavascriptbambolobredView Answer on Stackoverflow
Solution 11 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 12 - JavascriptChaosPandionView Answer on Stackoverflow
Solution 13 - JavascriptbdukesView Answer on Stackoverflow
Solution 14 - JavascriptkellotiView Answer on Stackoverflow
Solution 15 - JavascriptfinoView Answer on Stackoverflow
Solution 16 - JavascriptErik Martín JordánView Answer on Stackoverflow