Michał Gątkowski
Michał Gątkowski

Reputation: 91

Placing variable in JavaScript regex

I've got a regular expression like this one:

var reg = /http:\/\/s(\d+)\.de\.example\.com\/(.*?)\.php(.*)/i;

I want to have a variable, exactly this: ccode[i][2] in place of .de.

How do I do that? Thank for your help.

Upvotes: 1

Views: 47

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You need to use a RegExp constructor notation if you want to use variables in your regex pattern, and inside it, you need to double escape special regex metacharacters. I.e.

var reg = new RegExp("http://s(\\d+)\\." + ccode[i][2] + "\\.example\\.com/(.*?)\\.php(.*)", "i");

From MDN:

Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

Sample code:

var ccode = "de";
var reg = new RegExp("http://s(\\d+)\\." + ccode + "\\.example\\.com/(.*?)\\.php(.*)", "i");

alert(reg.test("http://s123.de.example.com/something.php?some=params"));

Upvotes: 3

Keerthi
Keerthi

Reputation: 923

Try this

var reg = '/http:\/\/s(\d+)\\'+ccode[i][2]+'\.example\.com\/(.*?)\.php(.*)/i';

Upvotes: 0

Related Questions