Bernard's Technocratic Blog


Javascript exec()
March 25, 2012, 10:13 pm
Filed under: JavaScript | Tags: , ,

While working on some problems requiring regular expression pattern matching, I came across something that was new to me.

It is the use of (RegEx Object).exec().

The exec() method is applied on a regular expression pattern, and takes a string as argument (the string in which to search for the pattern).

The exec() method returns null if no match was found, or an array containing the matching results when successful. The matching strings are incrementally added to the returned array, which means that you can search while returning results, using a JavaScript while-loop.

This is what is interesting.  Usually, one would expect all matches to be inserted into one returned array where one can loop through the array; however, this is not the case.

Remember: the exec() method returns either an array, if it found at least one match, or null, if it did not find any match.

Here is some code:

//enter a valid Roman Numeral string
function test(str)
{
   var regex = /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g;
   while(m = regex.exec(str))
   alert(m[0]);
}

test("XVII");