Regex question: How can I avoid the internal count of the '.test' function going up?

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!

you could reset the lastIndex property of the regex to 0

less hacky: if the match property doesn’t match, it returns null, you could check that before treating the output of match as an array

add the word javascript in the line with the three backticks above the block of code and it will be formatted as javascript

1 Like