Page 1 of 1

Concatenating RexExp Patterns in Javascript

Posted: Mon Nov 16, 2009 3:13 pm
by david64
If I have a string like this in JavaScript:

Code: Select all

str ='http://domain http://domain http://domain';
and use the following:

Code: Select all

var domain = 'domain';
var txt = new RegExp( "http://" + domain, "gim" );
var res = txt.exec( str );
alert( res );
It will only return [http://domain] once, even though I am using the g flag.

Likewise, I can't do it like this:

Code: Select all

 
var domain = 'domain';
var pat = /http:\/\/ + domain + /g
var res2 = str.match(pat);
alert( res2 );
Because it seems you can't concatenate regex literals in JS.

I need to be able to have a dynamic patter that will catch multiple results. Does anyone know either:

a - if and how you can concatenate literal patterns
b - if you can get the 1st example to store all the results (global)

?

Re: Concatenating RexExp Patterns in Javascript

Posted: Mon Nov 16, 2009 3:21 pm
by david64
Solved:

Code: Select all

var res2 = response.html.match( "http://" + "domain", "g" );
Although I haven't seen this documented anywhere.