Skip to content Skip to sidebar Skip to footer

Regular Expression Exec Function Does Not Work Multiple Times

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(t

Solution 1:

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);

Post a Comment for "Regular Expression Exec Function Does Not Work Multiple Times"