javascript - Regex test function do not return the same depending quotes -
i have weird case regular expression in javascript:
var re = /[^\s]+(?:\s+|$)/g; re.test('foo'); // return true re.test("foo"); // return false is regular expression type sensitive? first goal extract word (separated 1 or more whitespace) of string.
thanks help.
julien
when using g flag on javascript regular expression, keep track of last match found , start searching index next time try find match.
between 2 re.test() calls, take @ re.lastindex see talking about.
for example:
var re = /[^\s]+(?:\s+|$)/g; re.test('foo'); // return true re.lastindex; // 3 re.test("foo"); // return false you notice type of quotes use not matter, re.test('foo'); re.test('foo'); have same behavior.
if want regex start fresh, can either remove global flag regex or set re.lastindex 0 after each attempt find match, example:
var re = /[^\s]+(?:\s+|$)/g; re.test('foo'); // return true re.lastindex = 0; re.test("foo"); // return true the alternating noted blender in comments can explained because lastindex automatically set 0 when match fails, next attempt after failure succeed.
Comments
Post a Comment