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!

1
  • @FelixKling: ah, yes. Sorry for re.asking... Commented Jan 16, 2013 at 13:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

ok. let me try if I can fit this into my function.
ok. Worked. Thank you very much!
You're welcome, I'm glad that my answer helped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.