2

Possible Duplicate:
Javascript Regex: How to put a variable inside a regular expression?

I'm using the following for as regex pattnern in a sinon.js fakeServer response:

/https:\/\/ca-davstorage:8080\/myFile.json(\?.*|$)/

I would like to replace myFile with a variable, but as I'm not really good at regex, I'm struggling to get it to work. Currently I have this, but it does not seem to work.

'https:\\/\\/ca-davstorage:8080\\/'+myFile+'.json(\\?.*|$)/'

Question:
How to I correctly add a variable to a regex?

Thanks for help!

Community
  • 1
  • 1
frequent
  • 27,643
  • 59
  • 181
  • 333

1 Answers1

5

Instead of using /regex/ use the constructor function RegExp.

Example:

var foo = 'bar',
    re = new RegExp('[0-9]' + foo, 'g');
re.test('1bar'); //true

The first argument of the RegExp constructor is the regular expression, the second one is the modifier.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68