我想删除字符串的第一个字符,如果第一个字符是0。0可以出现不止一次。

是否有一个简单的函数可以检查第一个字符并在它为0时删除它?

现在,我正在尝试使用JS slice()函数,但这是非常尴尬的。


当前回答

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

你可以使用substring() javascript函数。

其他回答

另一个答案

str.replace(/^0+/, '')

你试过子字符串函数吗?

string = string.indexOf(0) == '0' ? string.substring(1) : string;

这里有一个参考- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

对于多个0,你总是可以这样做:

while(string.indexOf(0) == '0')
{
    string = string.substring(1);
}

try

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

console.log(“0 = > "字符串,字符串“0”.replace (/ ^ 0 / ")); console.log(“00字符串= >”,“00字符串“.replace (/ ^ 0 / ")); console.log(“string00 = >”,“string00”.replace (/ ^ 0 / "));

你可以用substring方法:

let a = "My test string";

a = a.substring(1);

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

另一种方法是在删除后获取第一个字符:

// 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'