JavaScript
Article
By Sam Deering

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

By Sam Deering

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 = '';

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

--ADVERTISEMENT--

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 = '';

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.

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account