Please note that this is not a question about regex themselves, it's about some weird behaviors I am detecting. I'm experiencing several tricky behaviors with javascript regular expressions. If I evaluate each code step individually, it works as expected so I think I may be incurring in some kind of state problem within regular expressions.
The first problem It's that I can not directly access the index of a regex exec result. For example
const regex = /a(bc)/gm;
regex.test('abc') && regex.exec('abc')[1] // => can not acces 1 of null
I tried saving the result to a variable and then try to conditionally access the value, but then I am always getting false
const doRegex = str => {
const regexRes = randomRegex.exec(str);
return randomRegex.test(str) ? regexRes[1] : str
}
console.log(doRegex('abc')) // => prints abc instead of bc
It was very hard to figure out a good title for the issue, so any suggestion to update is welcome.