How to do multiple replace using variable as first parameter?


When I want to do a replace on all occurrences of a string I do this:

var ola= "ola mundo ola mundo";

ola = ola.replace(/ola/g, "xxx");

Result: "xxx world xxx world";

But I want to use a variable instead of putting the word explicit, like this:

var ola= "ola mundo ola mundo";
var variavel= "ola";

ola = ola.replace(/variavel/g, "xxx");

I just do not know how to concatenate this to work. I've tried it in some ways and it did not work.

asked by anonymous 23.02.2015 / 22:04

2 answers


In this case you have to create a regular expression using the constructor to generate the RegExp object:


new RegExp (variable [ flag])


var string = "ola mundo ola mundo";
var variavel = "ola";
var regexp = new RegExp(variavel, 'g');
string = string.replace(regexp, "xxx");
alert(string); // dá "xxx mundo xxx mundo"

jsFiddle: link

23.02.2015 / 22:08

You can do this:

var ola = "ola mundo ola mundo";
var variavel = "ola";

var re = new RegExp(variavel, 'g');
ola = ola.replace(re, 'xxx');

alert(ola); // xxx mundo xxx mundo


Instead of using /regex/ you can create a new RegExp , giving the possibility of passing a string or a variable.

new RegExp(pattern[, flags])
where pattern is the regular expression ( in this case will be a variable ) to be used and flags in> to be used, for example% global match.

23.02.2015 / 22:08