Javascript Replace with variable in string with Regular Expression -
i want replace lot of keywords in string pre-defined variables, samples below, $1 shows variable name, not variable content, 1 can me, please!!!
correct:
1111{t:aa}
2222{t:bb}
3333{t:cc}
to:
1111test1
2222test2
3333test3
not:
1111aa
2222bb
3333cc
code:
var aa = "test1"; var bb = "test2"; var cc = "test3"; var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}"; var str_after = str_before.replace(/\{t:\s*(\w+)\}/g, "$1"); alert(str_before+"\n\n"+str_after);
a regexp constant (i.e. /.../
syntax) cannot directly refer variable.
an alternate solution use .replace
function's callback parameter:
var map = { aa: 'test1', bb: 'test2', cc: 'test3' }; var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}"; var str_after = str_before.replace(/{t:(\w+)}/g, function(match, p1) { return map.hasownproperty(p1) ? map[p1] : ''; });
this further has advantage mapping name value configurable, without requiring separately declared variable each one.
Comments
Post a Comment