Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex test function do not return the same depending quotes

I have a weird case with a regular expression in javascript:

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

Is a regular expression type sensitive? My first goal is to extract all word (separated by one or more whitespace) of a string.

Thanks for your help.

Julien

like image 603
JuSchz Avatar asked Apr 18 '13 19:04

JuSchz


1 Answers

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

Between the two re.test() calls, take a look at re.lastIndex to see what I am talking about.

For example:

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 quotes you use does not matter, re.test('foo'); re.test('foo'); will have the same behavior.

If you want the regex to start fresh, you can either remove the global flag from your regex 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 alternating noted by Blender in comments can be explained because lastIndex is automatically set to 0 when a match fails, so the next attempt after the failure will succeed.

like image 142
Andrew Clark Avatar answered Oct 21 '22 00:10

Andrew Clark