Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Convert a String to Regular Expression

Tags:

javascript

I want to convert a string that looks like a regular expression...into a regular expression.

The reason I want to do this is because I am dynamically building a list of keywords to be used in a regular expression. For example, with file extensions I would be supplying a list of acceptable extensions that I want to include in the regex.

var extList = ['jpg','gif','jpg'];

var exp = /^.*\.(extList)$/;

Thanks, any help is appreciated

like image 786
neolaser Avatar asked Dec 16 '22 18:12

neolaser


2 Answers

You'll want to use the RegExp constructor:

var extList = ['jpg','gif','jpg'];    
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');

MDC - RegExp

like image 179
ChaosPandion Avatar answered Dec 19 '22 07:12

ChaosPandion


var extList = "jpg gif png".split(' ');
var exp = new RegExp( "\\.(?:"+extList.join("|")+")$", "i" );

Note that:

  • You need to double-escape backslashes (once for the string, once for the regexp)
  • You can supply flags to the regex (such as case-insensitive) as strings
  • You don't need to anchor your particular regex to the start of the string, right?
  • I turned your parens into a non-capturing group, (?:...), under the assumption that you don't need to capture what the extension is.

Oh, and your original list of extensions contains 'jpg' twice :)

like image 45
Phrogz Avatar answered Dec 19 '22 08:12

Phrogz