Replace first character of string

后端 未结 7 837
走了就别回头了
走了就别回头了 2020-12-05 23:01

I have a string |0|0|0|0

but it needs to be 0|0|0|0

How do I replace the first character (\'|\') with (\'\'

相关标签:
7条回答
  • 2020-12-05 23:32
    "|0|0|0|0".split("").reverse().join("")  //can also reverse the string => 0|0|0|0|
    
    0 讨论(0)
  • 2020-12-05 23:41

    You can do exactly what you have :)

    var string = "|0|0|0|0";
    var newString = string.replace('|','');
    alert(newString); // 0|0|0|0
    

    You can see it working here, .replace() in javascript only replaces the first occurrence by default (without /g), so this works to your advantage :)

    If you need to check if the first character is a pipe:

    var string = "|0|0|0|0";
    var newString = string.indexOf('|') == 0 ? string.substring(1) : string;
    alert(newString); // 0|0|0|0​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

    You can see the result here

    0 讨论(0)
  • 2020-12-05 23:42
    str.replace(/^\|/, "");
    

    This will remove the first character if it's a |.

    0 讨论(0)
  • 2020-12-05 23:42

    It literally is what you suggested.

    "|0|0|0".replace('|', '')
    

    returns "0|0|0"

    0 讨论(0)
  • 2020-12-05 23:49

    If you're not sure what the first character will be ( 0 or | ) then the following makes sense:

    // CASE 1:
    var str = '|0|0|0';
    str.indexOf( '|' ) == 0 ? str = str.replace( '|', '' ) : str;
    // str == '0|0|0'
    
    // CASE 2:
    var str = '0|0|0';
    str.indexOf( '|' ) == 0? str = str.replace( '|', '' ) : str;
    // str == '0|0|0'
    

    Without the conditional check, str.replace will still remove the first occurrence of '|' even if it is not the first character in the string. This will give you undesired results in the case of CASE 2 ( str will be '00|0' ).

    0 讨论(0)
  • 2020-12-05 23:55
    var newstring = oldstring.substring(1);
    
    0 讨论(0)
提交回复
热议问题