From what I can tell, your string spans multiple lines, but you're not using the
m (multiline) modifier. As a result, your regex is only matching one of the two lines. Why it chooses to match the second line, I'm not sure, to be honest.
As for why
regex1.test("Item:8") gives you both
true and
false alternatingly, I'm not entirely sure either. What I do know is that the
g modifier stands for "global", which means the regex won't stop at the first match, and will instead keep matching until it reaches the end of the string (this might be the reason why only the last line is matched when not using the
m modifier). Naturally, the global modifier is necessary if you want to use
matchAll().
My guess is that the JavaScript engine isn't properly resetting the regular expression's state, which causes the second test to start from the end of the string. That explanation doesn't really make much sense to me, though, so if you're really curious, I recommend asking on
StackOverflow. You might receive an answer from someone who's much more knowledgeable about regex.
So the regex you need is actually:
JavaScript:
const regex1 = /Item:\d+/gm;
By the way, Microsoft has a Regular Expressions Cheat Sheet PDF which you can download here:
It's actually pretty useful when working with regex.
Just in case the download link breaks, it was found on this page:
The content that you're looking for is now retired.
learn.microsoft.com
Worst case you can search for "regex cheat sheet".