Echo JS 0.11.0

<~>
jylauril 3450 days ago. link 4 points
Short answer to your question: yes, global modifier makes the RegEx instance "stateful".

Here's the reason: When you define a global modifier, the RegExp object keeps track of the lastIndex. Second time you run it and it doesn't match anymore, it resets it back to 0. You can access it by wtf.lastIndex. This is a writable property that you can reset back to 0 manually.

The reason why you don't see more people having problems with this is mostly because many people are misusing regexp literals by not caching the pattern. ie. always checking with /foo/.test(myString), which creates a NEW RegExp instance every time that is run.

You probably know this already, but just wanted to mention this to anyone not familiar with regular expressions: there's two things wrong with doing: /^foo$/g.test('foo')

1. You're expecting the expression to be very strict by demanding the matching string to start(^) and end($) with what you specified, which renders the global modifier redundant.

2. The purpose of the test() -method is to see if this expression matches once or more, so again the global modifier is redundant.

Replies