2012-10-04

The Node.js REPL and Backslashes in Strings

I thought there was something weird going on with the node.js REPL's handling of backslashes in Strings. I was thinking, "Why are there twice as many backslashes!?" Then, it hit me: the output is correct! It is escaping the value of the string, just as if a programmer were to have typed it. Duh. You can use the output as-is when copy-and-pasting. No need to manually add extra backspaces! That's pretty convenient, eh? This really had me confused me at first, though, because I am so used to the behavior of Chrome's console, which prints out the unescaped string values (even though it does put quotes around the value).

$ node
> "\ "
' '
> JSON.stringify("\ ")
'" "'
> "\\"
'\\'
> JSON.stringify("\\")
'"\\\\"'
> new Buffer("\\")
<Buffer 5c>
> new Buffer([0x5c]).toString()
'\\'
> new Buffer([0x5c, 0x5c]).toString()
'\\\\'