我需要匹配数组中字符串中的数字。
['peter1','peter2','peter4'] ==> [1,2,0]
我想为第一个字符串的/1/g
的每个字符串设置正则表达式,为第二个字符串设置/2/g
,依此类推。
答案 0 :(得分:3)
您不需要regexp - 您只是想查看字符串是否包含索引,您可以使用indexOf
或includes
查看该索引。
const inputs = ['peter1','peter2','peter4'];
const output = inputs.map((str, i) => str.includes(i + 1) ? i + 1 : 0)
console.log(output);
答案 1 :(得分:2)
您可以使用地图功能...
0
。
const a = ['peter1','peter2','peter4']
const b = a.map((s, i) => parseInt(/\d+/.exec(s).pop()) === i + 1 ? i + 1 : 0)
console.info(b)