3
var ts = "00:00:06,705";

var regularExpression = /([0-9]+):([0-9]{2}):([0-9]{2}),([0-9]{3})/g;
var parsedTs1 = regularExpression.exec(ts);
var parsedTs2 = regularExpression.exec(ts);

The parsedTs1 shows a right result, but the parsedTs2 variable has null after running this script.

But when we removed the last 'g' character at the end, this works well.

The option flag g means, according to the document, global search, which is nothing to do with this case.

How can we use the defined regular expression string multiple times to match strings?

Jeungmin Oh
  • 364
  • 2
  • 15

1 Answers1

6

Quote from here:

Regular expression objects maintain state. For example, the exec method is not idempotent, successive calls may return different results. Calls to exec have this behavior because the regular expression object remembers the last position it searched from when the global flag is set to true.

If you want to call it multiple times you can manually reset the last index after each call:

var parsedTs1 = regularExpression.exec(ts);
regularExpression.lastIndex = 0;
var parsedTs2 = regularExpression.exec(ts);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • A better quote and explanation can be found at http://stackoverflow.com/questions/11477415/why-does-javascripts-regex-exec-not-always-return-the-same-value. – Wiktor Stribiżew Aug 12 '16 at 07:02