String.prototype.match()
and RegExp.prototype.exec()
are similar in both finding multiple occurrences and returning them in an array. Yet exec method returns an array of more detailed information. For instance unlike match it can find multiple occurrences of the capture groups as well. So if you have capture groups, exec is essential. One thing to keep in mind when working with exec you shouldn't invoke if from a literal regexp. Assign your regex to a variable first and use it to call your exec method from. One other thing is, while match would bring multiple occurrences in an array of items at one go, with exec you have to iterate for each occurrence to be captured.
Invoking match is fairly simple. Since it is a string prototype method you just chain it to a string and provide a regexp as an argument to the match method like; "test".match(/es/) A literal representation of a regex can be used with no problem.
Invoking exec is more complicated. As i mentioned previously it's best to have the regex assigned to something previously. Ok lets see an example
var text = '["job name 1","nat 1"],["job name 2","nat 2"],["job name 3","nat 3"]',
reg = /([^"]+)","([^"]+)/g,
tm = [],
te = [];
tm = text.match(reg); // tm has result of match
while(te[te.length]=reg.exec(text)); // te has result of exec + an extra null item at the end
te.length--; // te normalized.
document.write("<pre>" + JSON.stringify(tm,null,2) + "</pre>\n");
document.write("<pre>" + JSON.stringify(te,null,2) + "</pre>\n");
As you see exec's result also includes the capture groups. The way i choose to populate te
array is somewhat unorthodox but i hate to use a temp array just in the conditional part of while loop. This looks to me much more neat. The only thing is, the final null to stop the while loop gets inserted to the end of te
array. Hence the following te.length--
instruction.
Edit: Now there is also the String.prototype.matchAll() functionality available in modern browsers which mostly lifts the burden of using exec over our shoulders. You may look another answer of mine to see that in action.