简体   繁体   English

Javascript拆分了一个字符串并删除了前导0

[英]Javascript split a string and remove leading 0

I am very new at jquery...how would I split a strings like this: 我是jquery的新手...我将如何分割这样的字符串:

readybuilt-ANT-133.pdf
readybuilt-VIC-041.pdf

so I get just the numbers 133 and 41 所以我只得到数字133和41

this what I tried thus far 这是我到目前为止尝试过的

var str = this.home_pdf;
          var res = str.split("-");
          var lotNumber = res[2].split(".");
          lotNumber = lotNumber[0];
          console.log(lotNumber);

this works well, but how would I remove the leading 0s? 这很好用,但是如何删除前导0?

Try parseInt ( lotNumber, 10 ) . 尝试 parseInt ( lotNumber, 10 ) It will not care about leading zeroes when given an appropiate radix parameter. 给定适当的基数参数时,它将不关心前导零。

\n

PS: obviously, regex is the way to go here. PS:显然,正则表达式是解决问题的方法。

A much better way is to use Bergi's method 更好的方法是使用Bergi方法

var str = "readybuilt-VIC-041.pdf";
var lotNumber = str.split(/\.|-0*/)[2];
console.log( lotNumber );

Parse the variable as an integer: 将变量解析为整数:

lotNumber = lotNumber[0];
lotNumber = parseInt(lotNumber,10);
console.log(lotNumber);

assuming that this.home_pdf contains the string, this should do the trick: 假设this.home_pdf包含字符串,这应该可以解决问题:

var str = this.home_pdf;
str=parseInt(str.replace(/\D/g,''));
if(str.match(/^0/g)){
    str=parseInt(str.replace(/0/,''));
    }

Yet another solution, using match() 另一个解决方案,使用match()

'readybuilt-ANT-133.pdf'.match(/(?=[1-9])([0-9]+)/g);    // 133
'readybuilt-VIC-041.pdf'.match(/(?=[1-9])([0-9]+)/g);    // 41

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM