Rohan
Rohan

Reputation: 3795

JavaScript regex using strings?

How can I use strings as the 'find' in a JS regex?

i.e.:

var find = ["a", "b", "c"];
var string = "abcdefghijkl";

Now, I want to replace all the elements of the array find, with a blank string ( " " ), using regular expressions. How can I do this?

I mean, using .replace(/find[i]/g, "") in a loop wouldn't work.

So, how can I do it?

Thanks!

Upvotes: 0

Views: 183

Answers (3)

Guffa
Guffa

Reputation: 700362

If you need to run the expressions one at a time (for exampe if they are too complex to just concatentate into a singe expression), you create Regexp objects in a loop like this:

var find = ["a", "b", "c"];
var string = "abcdefghijkl";

for (var i = 0; i < find.length; i++) {
  var re = new Regexp(find[i], "g");
  string = string.replace(re, "");
}

Upvotes: 0

Salil
Salil

Reputation: 47482

Why don;t you use just

.replace(find[i], "*")

Upvotes: 0

gblazex
gblazex

Reputation: 50109

You can dynamically create regex with the built-in RegExp object.

var find = ["a", "b", "c"];
var re = new RegExp( find.join("|"), "g" ); // <- /a|b|c/g
var string = "abcdefghijkl";

string = string.replace(re, "");

alert(string); // <- defghijkl
​

Upvotes: 3

Related Questions