Reputation: 69
I have one regular expression:
var regex = /[..·・⋯•。~~〜><'"()%/\\]/g;
And I'm trying to define the pattern as string, then declare it as regular expression like this:
var charToFiltered = `[..·・⋯•。~~〜><'"()%/\\]`;
var regexA = new RegExp(charToFiltered, 'g');
But I get the following Error:
Invalid regular expression: /[..·・⋯•。~~〜><'"()%/]/: Unterminated character class
Upvotes: 1
Views: 2999
Reputation: 3527
It works if you move backslash to the start of the character set:
var charToFiltered = `[\\..·・⋯•。~~〜><'"()%/]`;
var regexA = new RegExp(charToFiltered, 'g');
console.log(regexA);
The reason for that is your \\
turns into single backslash and then you have \]
construction in your regexp which means ]
literally. So your closing bracket becomes a part of the character class, and then you miss the actual closing ]
. All you need to do to resolve that is to move the backslash to someplace where it doesn't escape anything.
Upvotes: 2