Placing variable in JavaScript regex -


i've got regular expression one:

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

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

how do that? thank help.

you need use regexp constructor notation if want use variables in regex pattern, , inside it, need double escape special regex metacharacters. i.e.

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

from mdn:

use constructor function when know regular expression pattern changing, or don't know pattern , getting source, such 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"));


Comments