Invalid regular expression flag
yllhwa opened this issue · 2 comments
yllhwa commented
reproduction code:
const espree = require("espree");
var code = `let pattern = /(\/x\/[\w-_]+\/)/;`;
var ast = espree.parse(code, { ecmaVersion: 6 });
console.log(ast);
the regular expression looks fine(since I can run the code below)
let url = "/pre/x/test/";
url = url.replace(/(\/x\/[\w-_]+\/)/, "$1append/")
console.log(url)
but an error occurred:
espree\dist\espree.cjs:679
throw err;
^
SyntaxError: Invalid regular expression flag
at Espree.raise (espree\dist\espree.cjs:674:25)
at pp$1.validateRegExpFlags (acorn\dist\acorn.js:3945:14)
at pp.readRegexp (acorn\dist\acorn.js:5540:10)
at pp.readToken_slash (acorn\dist\acorn.js:5315:53)
at pp.getTokenFromCode (acorn\dist\acorn.js:5478:19)
at pp.readToken (acorn\dist\acorn.js:5195:17)
at pp.nextToken (acorn\dist\acorn.js:5186:17)
at pp.next (acorn\dist\acorn.js:5147:10)
at pp$9.eat (acorn\dist\acorn.js:702:12)
at pp$8.parseVar (acorn\dist\acorn.js:1320:16) {
index: 15,
lineNumber: 1,
column: 16
}
Node.js v20.10.0
version: 9.6.1
fasttime commented
Note that backslash characters in template literals create escape sequences, so the code
in your example is not what it looks like:
var code = `let pattern = /(\/x\/[\w-_]+\/)/;`;
console.log(code);
// prints "let pattern = /(/x/[w-_]+/)/";
To get the text as it appears inside backticks, you could use String.raw
:
var code = String.raw`let pattern = /(\/x\/[\w-_]+\/)/;`;
Or insert a double backslash (\\
) where there should be one:
var code = `let pattern = /(\\/x\\/[\\w-_]+\\/)/;`;
yllhwa commented
Thanks a lot.
I just made such a silly mistake.
Esprima cannot parse this, so I want to try espree. And it works!