regex - Pass a variable to a RegExp with symbol JavaScript -
i generate output mr. x born on 01-01-2000 using following code
var str="%(name)s born on %(date)s", replace={name:'mr.x',date:'01-01-2000'}, subject=["name","date"]; subject.map(function(data){ var regex = new regexp("%("+data+")s", 'g'); str=str.replace(regex,replace[data]) }) console.log(str);
i cant able replace dynamic variable symbol 1 me find better solution thanks.
just escape (
, )
has special meaning in regex, used grouping (matches).
var regex = new regexp("%\\("+data+"\\)s", 'g');
running code:
var str="%(name)s born on %(date)s", replace={name:'mr.x',date:'01-01-2000'}, subject=["name","date"]; subject.map(function(data){ var regex = new regexp("%\\("+data+"\\)s", 'g'); str=str.replace(regex,replace[data]) }) document.write(str);
Comments
Post a Comment