0

I have the following orginal code of preg match

for(var i = 0;i<5;i++)
{ 
patt1 = /Colour1\/(\d+)"/; 
var ab=(data.match(patt1)[1]); 
alert(ab);
}

I am wondering if i can use the variable i instead of 1(for 5 loops),like below example.I can use the value i outside but not inside pregmatch.

 for(var i = 0;i<5;i++)
{<br>
patt1 = /Colour"+i+"\/(\d+)"/; 
var ab=(data.match(patt1)[1]); 
alert(ab);
} 
vishnu
  • 869
  • 1
  • 16
  • 25
  • This should answer your question: http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript – travega Jan 25 '12 at 19:42

3 Answers3

1

You'll have to use the RegExp constructor:

for (var i = 0; i < 5; i++)
{
    var patt1 = new RegExp('Colour' + i + '/(\\d+)"'),
        ab = (data.match(patt1) || [])[1]; 
    alert(ab);
}

Remember to double escape your slashes!


See it here in action: http://jsfiddle.net/q2C55/

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

Like this?

var ab = data.match('Colour'+i+'/(\\d+)"')[1];
Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
1

Sure

patt1 = new RegExp("Colour"+i+"/(\\d+)\""); 

but you could also skip the loop

patt1 = new RegExp("Colour[0-4]/(\\d+)\"");
  • @JustinBiaber: You're welcome. I just updated it to require the closing `"` in the regex. If that's not needed, remove the `\"`. –  Jan 25 '12 at 19:52