In JavaScript, string '\m' is fully equals to string 'm', why?

Viewed 90

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.

2 Answers

\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.

Related