Regular Expression Test does not return the same dependent quotation marks

I have a weird case with regex in javascript:

var re = /[^\s]+(?:\s+|$)/g; re.test('foo'); // return true re.test("foo"); // return false 

Is the regular expression type sensitive? My first goal is to extract all the words (separated by one or more spaces) lines.

Thank you for your help.

Julien

+6
source share
1 answer

When using the g flag in a Javascript regular expression, it will track where the last match was found, and start searching from that index the next time you try to find a match.

Between the two calls to re.test() look at re.lastIndex to find out what I'm talking about.

For instance:

 var re = /[^\s]+(?:\s+|$)/g; re.test('foo'); // return true re.lastIndex; // 3 re.test("foo"); // return false 

You will notice that the type of quotation marks you use does not matter, re.test('foo'); re.test('foo'); re.test('foo'); re.test('foo'); will have the same behavior.

If you want the regular expression to start from scratch, you can either remove the global flag from your regular expression or set re.lastIndex to 0 after each attempt to find a match, for example:

 var re = /[^\s]+(?:\s+|$)/g; re.test('foo'); // return true re.lastIndex = 0; re.test("foo"); // return true 

The alternative comment noted by Blender in the comments can be explained because lastIndex automatically set to 0 when the match fails, so the next attempt after failure will succeed.

+10
source

All Articles