I just discovered something that I don’t quite understand when checking Reg.Exp.lastIndex.
I don’t understand why it would produce 0 rather than 9 when it is directly applied to it without using a variable.
Because you haven’t used any methods on that RegExp object. The point of lastIndex is to be useful if you are repeatedly applying a regex pattern to a string. So in the example, the test method is used on a string. The test runs, and the lastIndexfor that particular instance of RegExp is incremented to 9. Then test could be ran again, now starting at that index, and so on. You haven’t done anything with the RegExp object on your last line, so the lastIndex is 0
Well if I rewrite this particular example, this is exactly the same as what you’ve just written one post up, but possibly clearer w/r/t what’s confusing you:
Thanks for the example. Yes, I understand your point.
But now I am stuck with why using /foo/g directly does not produce the same results… like the example I showed above.
Because every time you write /foo/g, that’s a new object, a new instance of RegExp. Every time you do it, you are doing new RegExp("foo", "g"): the /foo/g syntax is just sugar for that. Every time you construct a new RegExp object, it’s lastIndex property starts at 0. So lastIndex is only useful if you assign your newly created RegExp object to a variable then reuse it.