3

console.log('\d' === 'd'); // true

Character 'd' is not a special character, why javascript want to slice the escape notation. It's better to keep the escape notation in my view.

When I want to fully match string-'\d' using regular expression, it just impossible! Taking the following code as an example.

console.log(RE.test('\d')); // it should log true 
console.log(RE.test('d'));  // it should log false              

Unfortunately, you just cannot figure out a regular expression pattern.

customcommander
  • 17,580
  • 5
  • 58
  • 84
quan lili
  • 109
  • 6
  • 1
    `\d` is an escaped `d` character. There is no escape sequence for that, so you just get a literal `d` as string content. This seems like [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - please focus on the actual problem you are trying to solve because escaping characters is surely not it. – VLAZ May 28 '20 at 07:08

2 Answers2

6

You have no reason to escape d in a string and JavaScript ignores it. If you need \d you need to escape the escape character: \\d.

See also Why do linters pick on useless escape character?

customcommander
  • 17,580
  • 5
  • 58
  • 84
  • So it just syntax of javascript language. There does not exist a string like '\d' in javascript. Right? – quan lili May 28 '20 at 07:18
  • 1
    @quanlili Strings can have `\d`, but string _literals_ cannot. If you want to use a `\ ` in a string literal, then you need to escape that backslash with another one. Or use the `String.raw` function: `let s = String.raw\`\d\`` – Ivar May 28 '20 at 07:20
  • Yes, I see. Much thx. I have not used String.raw `\d` before. It can output a raw String. Amazing! – quan lili May 28 '20 at 07:27
3

\d has a special meaning in regular expressions (a digit character), but also in strings (escaped 'd' character, which is exactly like 'd').

Any / creates an escape sequence in a string. Some are "useful" (\n === new line) and some arguably useless (`'\d' === 'd').

If you want the regex \d, you could

1 - use a regex literal instead : /\d/

2 - escape the \ in the string : '\\d', so that the string containing the two characters \ and d is correctly understood by Javascript.

Pac0
  • 21,465
  • 8
  • 65
  • 74