console.log(/\.js$/.toString() === '/\.js$/') // false
// or
console.log(/\.js$/.toString() == '/\.js$/') // false
// but
console.log(/\.js$/.toString()) // /\.js$/
console.log(/\.js$/.toString() === /\.js$/.toString()) // true
- 4,431
- 2
- 27
- 39
4 Answers
Because when converted to a string, the meaning of \ changes. In a string, it is used to escape characters, such as \n and \t. In a regex, it means to take the next character literally, such as . in your case. Thus, when converted to a string \ must be escaped, so /\.js$/ becomes "/\\.js$/". Note that if you then feed this into the RegExp constructor, "\\.js$" would be valid, whereas "\.js$" would have a different meaning, and be interpreted as /.js$/
- 4,611
- 2
- 16
- 33
\ is a special char in string literals to escape the next char. Use 2 of them.
console.log(/\.js$/.toString() === '/\\.js$/') // true
- 187,200
- 47
- 362
- 445
Because the string '/\.js$/'becomes /.js$/ this happens because '.' in js is actualy the scaped character .
So basically you are comparing '/\.js$/' with /.js$/ that are different strings.
to achieve get the same strings you need to escape the / by changing your string literal to '/\\.js$/'
- 4,051
- 3
- 25
- 33
See the difference your self, console.log(/\.js$/.toString()); prints /\.js$/ while console.log('/\.js$/'); prints \.js$/ which is obviously different.(so you are getting false as both string are different)
console.log(/\.js$/.toString());
console.log('/\.js$/');
- 2,901
- 2
- 15
- 25