0

I want to create new a RegExp with variable by JavaScript. But I got trouble when I want to create new a lookaround RegExp:

var xvar = "_on";
var regex = new RegExp("(?<!" + xvar + ")(.gif|.jpg|.png)$");
#=> SyntaxError: Invalid regular expression: /(?<!_on)(.gif|.jpg|.png)$/: Invalid group

I tried to escape all special characters follow Creating regexp with special characters, then it can create a new RegExp but just like a string, not a lookaround regex.

/\(\?<!_on\)\(\.gif\|\.jpg\|\.png\)\$/

Can anyone help me?

Community
  • 1
  • 1
yeuem1vannam
  • 957
  • 1
  • 7
  • 15

1 Answers1

-2

I don't know your goal of RegExp but quantifier (...) causes error in this situation. For example, use non-capturing parentheses (?:...).

var regex = new RegExp("(?:<!" + xvar + ")(?:.gif|.jpg|.png)$");

Refer to: Regular Expressions - JavaScript | MDN.

@Alan Moore: you're right.

tokkonopapa
  • 167
  • 4
  • 4
    He's not trying to match `<!`, he's trying to use a negative lookbehind, which is not supported in JavaScript regexes. – Alan Moore Aug 26 '13 at 08:46