Fix for 'Invalid regular expression flags' error: escaped slashes in template literals break inline scripts
A server-rendered page can fail in the browser with a SyntaxError when a regex containing an escaped slash is written inside a JavaScript template literal. The template literal strips the backslash, so the regex ends early and the rest is read as flags, which halts the entire inline script without any server-side error. The recommended fix is to write slashes in emitted regexes as the character class [/], which survives multiple string-escaping layers, while doubled backslashes proved fragile. The author suggests finding affected code with ESLint's no-useless-escape rule and adding a test that parses every emitted inline script with new Function. The guidance applies only to code emitted as strings, since regex literals in ordinary .js files are fine.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in