Stiger Stiger - 6 months ago 59
AngularJS Question

How to create dynamic regex in javascript

I want to use

$htppBackend
to mock some service. My problem is some of service url have parameter, ex:
http://domain/service1?param1=a&param2=b


I need an regex which can reconize
http://domain/service1<whatever>
is correct for
http://domain/service1?param1=a&param2=b
. One thing, the first part
http://domain/service1
is not a constant, it can be
http://domain/service2/sth/anything
.

Please help. Thanks.

Edit:

I put my code here to make it easy to understand.

I have 4 api urls:

angular
.module('moduleName')
.constant('getApi', {
attrList: 'http://domain/setup/attrList',
eventList: 'http://domain/setup/eventList',
vcList: 'http://domain/api/list1',
getRaDetails: 'http://domain/abc/getDetails?raId={0}&bookId={1}'
});


With
attrList
,
eventList
and
vcList
, they are ok with
$httpBackend.whenGET(getApi.attrList).respond(responseObject);

$httpBackend.whenGET(getApi.eventList).respond(responseObject);

$httpBackend.whenGET(getApi.vcList).respond(responseObject);
.

But the last one
getRaDetails
, it doesn't work with
$httpBackend.whenGET(getApi.getRaDetails).respond(responseObject);
because
raId
and
bookId
have different value each times.

Now I need a regex to make this rule -
$httpBackend.whenGET(getApi.getRaDetails).respond(responseObject);
works with all
raId
and
bookId
value.

Hope it can explain my question more clearly. Thanks

Answer

This's my working code:

_(getApis).each(function (api) {
                var val = api.value.split('?')[0].replace(/\//g, '\\/'),
                    reg = new RegExp(val);

                $httpBackend.whenGET(reg).respond(dummy[api.key]);
            });

Thanks all.