Using jQuery .exec() and .compile() Regex

Sam Deering
Share

If your working with JavaScript regular expressions a lot (like me) this is worth knowing. For those of you that don’t know the exec() method simply tests for a match in a string and returns the matched text if it finds a match, otherwise it returns null.

/* match just the href of js includes */
var jsSrcRegex = /src="(.+?)"/igm; 

/* html for js include */
var html = '<script type="text/javascript" src="/jquery-1.6.1.min.js"></script>';

console.log(jsSrcRegex.exec(html));

console.log(html);
console.log(jsSrcRegex);

console.log(jsSrcRegex.exec(html));

regex-compile1

No results eh?! Interesting enough if we then add an extra console.log and… results are back! hmm…

regex-compile2

regex.compile() fixes the problem

Now, if you use .compile() on the regex it works!

/* match just the href of js includes */
var jsSrcRegex = /src="(.+?)"/igm; 

/* html for js include */
var html = '<script type="text/javascript" src="/jquery-1.6.1.min.js"></script>';

console.log(jsSrcRegex.exec(html));

/* recompile the regex */
jsSrcRegex.compile(jsSrcRegex);

console.log(html);
console.log(jsSrcRegex);

console.log(jsSrcRegex.exec(html));

As you can see the array of results is found once we recompiled.

regex-compile3

It basically compiles/recompiles the regex during code execution, so generally if you change the regex you should run .compile(). This also applies to using .exec() inside a loop just include .compile() before it. Useful to know.