匹配越来越多的数字

时间:2017-04-27 01:36:31

标签: javascript

我需要匹配数组中字符串中的数字。

['peter1','peter2','peter4'] ==> [1,2,0]

我想为第一个字符串的/1/g的每个字符串设置正则表达式,为第二个字符串设置/2/g,依此类推。

2 个答案:

答案 0 :(得分:3)

您不需要regexp - 您只是想查看字符串是否包含索引,您可以使用indexOfincludes查看该索引。

const inputs = ['peter1','peter2','peter4'];

const output = inputs.map((str, i) => str.includes(i + 1) ? i + 1 : 0)

console.log(output);

答案 1 :(得分:2)

您可以使用地图功能...

  1. 通过正则表达式提取号码
  2. 将其与当前基于1的索引进行比较,以将不同步的数字过滤为0
  3. 
    
    const a = ['peter1','peter2','peter4']
    
    const b = a.map((s, i) => parseInt(/\d+/.exec(s).pop()) === i + 1 ? i + 1 : 0)
    
    console.info(b)