Laelfaert
Laelfaert

Reputation: 1

JavaScript/Jquery Dynamic RegExp generation

I've searched this place a lot, and I'm stuck at that my regular expression works, but not dynamically.

id_name is the string that is picked dynamically. Then, the regexp should replace the match with a single var, which is in "vals". For some reason, when I code the regexp without the variable, it works as intended. I think I might do something wrong with the conversion to a regexp object.

Original String:

obj = values.replace(/{name}(.*?){\/name}/, 'igm');

Regexp Object:

        re = '\/{' + id_name + '}(.*?){\\/' + id_name + '}\/';
        regexp = new RegExp(re, 'igm');
        obj = values.replace(regexp, vals);

Thanks in advance!

Upvotes: 0

Views: 732

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

You don't need / and you also don't need to escape the character if you are constructing the regex via constructor:

re = '{' + id_name + '}(.*?){/' + id_name + '}';

Upvotes: 1

Related Questions