Home Ask Login Register

Developers Planet

Your answer is one click away!

Anoop LL February 2016

Replacing all match in a String

my string contains some variables which is given between @,eg:-(@name@). Am passing variables values and storing it in an array. I want to replace this values with the variable in actual string.

This is my code

actual_string = actual_string.replace(new RegExp('@'+dynamic[i]+"@"),value);

This will replace only one value, If i have same variable repeatedly then the above code will replace only the first occurance. Then i tried

actual_string = actual_string.replace(new RegExp('/\@'+dynamic[i]+"\@/"),value);

But this is not even replacing single variable


Rory McCrossan February 2016

You need to use the flags parameter of RegExp. Use a g to make the search global throughout the string. Try this:

actual_string = actual_string.replace(new RegExp('@' + dynamic[i] + "@", 'g'), value);

Post Status

Asked in February 2016
Viewed 1,872 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life