Search code examples
regexprettier

Prettier auto "correct" regex escaping forward slash `\`


pattern: '^131\.[0-9]{6}$',

prettier change it to pattern: '^131.[0-9]{6}$',. Is there a way to ignore line, or ignore file?


Solution

  • Assuming JavaScript (as you're using prettier.) The '^131\.[0-9]{6}$' is just a string, not a regex. Prettier removes unnecessary escape characters when reformatting. As \. isn't a meaningful escape, it's the same as just having . on its own in string context.

    Your aim is to get \. into a regex, which I assume you're going to create using the new RegExp() constructor; in that case you want to escape the backslash:

    pattern: '^131\\.[0-9]{6}$'