0

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 Answers 3

3

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
​
3
  • Don't need to use the wrapping parens here - just RegExp( find.join("|") ) will work fine. Commented Jul 5, 2010 at 15:17
  • 1
    While this will work for these simplified array contents, it will have bugs if the an item contains regex characters without escaping them. Commented Jul 5, 2010 at 15:19
  • @Jason in this case you can use something like preg_quote (from php.js): str = (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, '\\$1'); Commented Jul 5, 2010 at 15:25
0

Why don;t you use just

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.