I am not quite sure wether the question is clear enough, so here is an example:
let regex = /\d/g
let string = 'hello1234'
console.log([...string.matchAll(regex)])
/* this will return this:
[ [ '1', index: 5, input: 'hello1234', groups: undefined ],
[ '2', index: 6, input: 'hello1234', groups: undefined ],
[ '3', index: 7, input: 'hello1234', groups: undefined ],
[ '4', index: 8, input: 'hello1234', groups: undefined ] ]
*/
So this makes perfect sense. But now suppose I want to make sure, that my string matches my regex, before I log all of its matches to the console like this:
let regex = /\d/g
let string = 'hello1234'
if(regex.test(string) == false){
console.log('sorry, no matches')
} else {
console.log([...string.matchAll(regex)])
}
/* this will log this to the console:
[ [ '2', index: 6, input: 'hello1234', groups: undefined ],
[ '3', index: 7, input: 'hello1234', groups: undefined ],
[ '4', index: 8, input: 'hello1234', groups: undefined ] ]
*/
(By the way, how do you make multiline comments here?)
So with all that said and done, simple quesion:
Is there any neat way to avoid this, apart from just making the same regex two times, using one of them for testing and the other for logging all matches?
Thanks for your help!