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

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.

Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


  • rahendz

    how can i include variable in the middle of jsSrcRegex

    • http://jquery4u.com/ jQuery4u

      Something like this:var jsSrcRegex = /src=”(.+?)variable(.+?)”/igm; ?

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.