Javascript: convert string to regex

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

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

var extList = ['jpg','gif','jpg']; var exp = /^.*\.(extList)$/; 

Thanks, any help is appreciated

+4
source share
3 answers

You want to use the RegExp constructor:

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

MDC - RegExp

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

Note that:

  • You need to flush backslash twice (once for a string, once for a regular expression)
  • You can provide flags to the regular expression (e.g. case insensitive) as strings
  • You don’t need to bind your specific regular expression to the beginning of the line, right?
  • I turned your parens into a non-capture group (?:...) , assuming you don't need to commit what the extension is.

Oh, and your initial list of extensions contains "jpg" twice :)

+2
source

You can use the RegExp object:

 var extList = ['jpg','gif','jpg']; var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$"); 
+1
source

Source: https://habr.com/ru/post/1335356/


All Articles