2

I have a working example here: http://jsfiddle.net/R7KuK/

I've tried to create an array containing full regular expressions with regex delimiters and set flags, but the RegExp object parses given strings as strings, not as regular expressions.

  var regex = "/wolves/i"

vs.

  var regex = /wolves/i

My question is: How do I convert string-ed regex into an actual regular expression?


UPDATE: It wasn't until Felix King kindly explained to me that

var array = ["/wolves/i", "/Duck/"];

can safely become:

var array = [/wolves/i, /Duck/];
11
  • 2
    Check stackoverflow.com/questions/4589587/… and stackoverflow.com/questions/874709/… Commented Mar 7, 2012 at 20:53
  • 6
    Why don't you create the array as [/wolves/i, /Duck/]? Why do you use strings at all? That seems to be an unnecessary complication to me. Commented Mar 7, 2012 at 20:55
  • @FelixKling: I wasn't aware that was even possible, not to use the quotes. Commented Mar 7, 2012 at 20:57
  • How did you create regular expressions then? /.../ denotes a regex literal. You must have been using /.../.test(...) or str.match(/.../) before. Anyways, here is some documentation: developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions Commented Mar 7, 2012 at 20:58
  • @FelixKling: Yes, I've been using str.match(/.../), though I wasn't aware it was possible not to use strings in arrays, assuming regexp's could contain unescaped characters and fail; or I could be trying to match for a dot and accidentally close one array item. Commented Mar 7, 2012 at 21:02

2 Answers 2

3

Try this:

var regexSplit = regex.split( '/' );
var realRegex = new RegExp( regexSplit[1], regexSplit[2] );

Or better:

var regexMatch = regex.match( /^\/(.*)\/([^\/]*)$/ );
var realRegex = new RegExp( regexMatch[1], regexMatch[2] );

Better cause if your regex contains '/', the first one will fail. ;)

Sign up to request clarification or add additional context in comments.

Comments

0

as stolen from here:

Use the RegExp object constructor to create a regular expression from a string:

var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;

1 Comment

If you copy another answer verbatim, shouldn't this question be closed as a duplicate then?

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.