1

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.

1

2 Answers 2

3

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"));

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

Comments

0

Try this

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

1 Comment

I've tried it in console and.. Uncaught SyntaxError: Unexpected token ILLEGAL

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.