views:

44

answers:

3

Hi,

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!

+3  A: 

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
​
galambalazs
Don't need to use the wrapping parens here - just `RegExp( find.join("|") )` will work fine.
Peter Boughton
yeah i know, thanks :) just typed too fast
galambalazs
While this will work for these simplified array contents, it will have bugs if the an item contains regex characters without escaping them.
Jason Harwig
thanks, this is perfect!
Rohan
@Rohan you may accept the answer if it solved your problem: http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about/5235#5235
galambalazs
@Jason in this case you can use something like preg_quote (from php.js): `str = (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1');`
galambalazs
A: 

Why don;t you use just

.replace(find[i], "*")
Salil
That works only for the first occurrence.
Rohan
A: 

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, "");
}
Guffa