How to replace multiple using variable as first parameter?

Asked

Viewed 1,726 times

9

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

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 explicitly, in this way:

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

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

I just don’t know how to concatenate it to work. I’ve tried it in some ways and it didn’t work.

2 answers

8


Then you need to create a regular expression using the constructor to generate the Regexp object:

new Regexp(variable [, flag])

Example:

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: http://jsfiddle.net/Ldrynpsf/

6

You can do it like 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

DEMO

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

new RegExp(pattern[, flags])

Where Pattern is the regular expression (then it will be a variable) to be used and flags indicates the modifiers to be used, for example the g global match.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.