大家好,我正在从事一个项目,我发现自己需要从特定索引中的字符串中获取数字,例如:我有这个 id,我必须获取这两个数字(考虑到一个数字可以包含 1 个或多个数字,例如:1 或 12 )
id = stock_stockbundle_facturefounisseur_ligneffm_1_ligneff_1_idarticle
正如您所注意到的,id 在两个不同的部分中包含数字 1,因此我需要在该字符串中包含这两个数字! 我考虑过使用子字符串,但如果第一个数字包含多个数字,我可能会错过第二个数字
如果有人有想法, 提前非常感谢!!!
最佳答案
您可以使用正则表达式:
var id='stock_stockbundle_facturefounisseur_ligneffm_10_ligneff_2_idarticle';
var pattern=/\d+/g;
var res = id.match(pattern);
alert(res[0]); //will be 10
alert(res[1]); //will be 2
两个数字都存储在数组 res
如果您不关心两个数字之间的分割(因此您只需要“102”):
var id='stock_stockbundle_facturefounisseur_ligneffm_10_ligneff_2_idarticle';
var res = id.replace(/\D+/g,'');
alert(res); //will be 102
关于javascript - 如何从特定索引中获取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890358/