Brave Man Brave Man - 1 month ago 9
Javascript Question

Javascript replace comma seprated characters by using regex

I want to replace

@parm1,@parm2,@parm3...
etc with comma separated values using regular.how can i do this ?

Example



Input Data



My Name is
@parm1
and My father Name is
@parm2
and also my nick name is
@parm1
and i live in
@parm3




Replace with



James,Nortain,TEST Address


Result



My Name is
James
and My father Name is
Nortain
and also my nick name is
@parm1
and i live in
TEST Address

Answer

Try:

var str = "My Name is @parm1 and My father Name is @parm2 and also my nick name is @parm1 and i live in @parm3";
var values = "James,Nortain,TEST Address".split(",");
var result = str.replace(/@parm(\d+)/gi, function(a,b){
    return values[b-1] || a
});

document.write(result)

Comments