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

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

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


当前回答

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

其他回答

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

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

var s = "0test";
if(s.substr(0,1) == "0") {
    s = s.substr(1);
}

0: http://jsfiddle.net/An4MY/

String.prototype.ltrim0 = function() {
 return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();

try

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

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

String.prototype.trimStartWhile =函数(谓词){ If (typeof predicate !== "function") { 返回; } 让len = this.length; If (len == 0) { 返回; } 设s =这个,I = 0; While (i < len && predicate(s[i])) { 我+ +; } 返回s.substr(我) } 让str = "0000000000ABC", r = str.trimStartWhile(c => c === '0'); console.log (r);

你可以用substring方法:

let a = "My test string";

a = a.substring(1);

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