Delete first character of a string in Javascript

前端 未结 14 1459
名媛妹妹
名媛妹妹 2020-11-28 01:01

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

相关标签:
14条回答
  • 2020-11-28 01:34

    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);
    }
    
    0 讨论(0)
  • 2020-11-28 01:36

    You can do it with substring method:

    let a = "My test string";
    
    a = a.substring(1);
    
    console.log(a); // y test string
    
    0 讨论(0)
  • 2020-11-28 01:41

    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,'');
     }
    }
    
    0 讨论(0)
  • 2020-11-28 01:45

    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 );
    
    0 讨论(0)
  • 2020-11-28 01:47
    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();
    
    0 讨论(0)
  • 2020-11-28 01:48

    try

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

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

    0 讨论(0)
提交回复
热议问题