12

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

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

leogoesger
  • 3,476
  • 5
  • 33
  • 71
  • You can't do this because `.` has a special meaning in regex. You are escaping `.` to strip it of that meaning. So there is no way to do what you're asking. – TheChetan Oct 22 '17 at 19:33
  • 1
    @TheChetan that is awfully misleading. You can escape special characters in regex to be literal characters. "If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash" - https://www.regular-expressions.info/characters.html#Special_Characters – shriek Dec 13 '21 at 07:21
  • @shriek You're right, my understanding back then was incorrect. That comment is wrong and misguiding. – TheChetan Dec 13 '21 at 09:32

1 Answers1

14

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}$'
searlea
  • 8,173
  • 4
  • 34
  • 37
  • If his language of implementing was js, then \ escapes just as well. Not sure about other languages. – TheChetan Oct 22 '17 at 19:35
  • 2
    using \ itself does not work. I tried to use [.] and `\\.` , and both worked as expected. – leogoesger Oct 22 '17 at 20:31
  • 1
    also `.prettierignore` is an option to ignore certain files. You would add this file just like how you add `.gitignore`. – leogoesger Oct 23 '17 at 05:09
  • My original answer was rushed and poorly worded. I've reworded for clarity. – searlea Oct 23 '17 at 07:31
  • 1
    You can just use the literal notation to avoid prettier formatter stripping any slashes: `const regex = /^\S{8,}$/; regex.test('some string')` Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp – Patronaut Mar 18 '22 at 18:20
  • what about apostrophe escape in a project with `/*eslint quotes: ["error", "single", { "avoidEscape": false }]*/`. it seems that the only way for it is to use `.prettierignore`: example string: `'check the user\'s comment'` changes to `"check the user's comment"` and ESLint starts crying. – Amin Bakhtiari Far Mar 15 '23 at 11:38
  • 1
    @AminBakhtiariFar It's not really relevant to the original question, but I'd suggest you look at using https://github.com/prettier/eslint-config-prettier to disable the ESLint rules that conflict with prettier. (It's common practice to do this.) – searlea Apr 09 '23 at 09:45