Можете ли вы просто:
let names = string.match(regex_name).map(n => n.replace('name: ',''));
Вы также можете использовать matchAll
и извлечь группы:
const exp = new RegExp('name:\\s(.+)','g');
const matches = string.matchAll(exp);
const results = [];
for(const match of matches) {
results.push(match[1]);
}
Или функционально:
Array.from(string.matchAll(exp)).map(match => match[1]);
Длястарые версии узла:
const exp = new RegExp('name:\\s(.+)','g');
const results = [];
let match = exp.exec(string);
while(match) {
results.push(match[1]);
match = exp.exec(string);
}
const string = `
name: Mike
age: 11
name: Jake
age: 20
name: Jack
age: 10
`;
let names = string.match(/name:\s(.+)/g).map(n => n.replace('name: ',''));
console.log(names);
const exp = new RegExp('name:\\s(.+)','g');
const matches = string.matchAll(exp);
const results = [];
for(const match of matches) {
results.push(match[1]);
}
console.log(results);
console.log(Array.from(string.matchAll(exp)).map(match => match[1]));
//Node 8 Update
const results2 = [];
let match = exp.exec(string);
while(match) {
results2.push(match[1]);
match = exp.exec(string);
}
console.log(results2);