Reputation: 41
I want to generate the string "\" in Javascript but couldn't seem to do it. If I only write "\", I would get compile time error because " itself is escaped. But if I do "\\", I would get two slashes as the output. So how do I generate a string with a single forward slash?
Upvotes: 1
Views: 6206
Reputation: 163301
The character /
is a slash. The character \
is a backslash.
Backslash \
is used as an escape character for strings in JavaScript, and in JSON. It is required for some characters to remove ambiguity from string literals. This string is ambiguous:
'He's going to the park'
There are three single quote '
marks, and the parser doesn't know what is part of the string and what isn't. We can use a backslash to escape the one that we want to represent the character '
instead of the close of the string literal (also '
).
'He\'s going to the park'
Now, if the backslash has special meaning, how do we represent a literal backslash \
character in the string? By simply escaping the backslash \
with a backslash \
.
'C:\\DOS\\command.com' // In memory this is: C:\DOS\command.com
Remember that this escaping is only for the text representation of strings in code or JSON. The code is parsed and the strings in memory are what we would expect, with all escaping resolved to the proper characters.
Now your question asks about JSON and makes the assumption that this is incorrect:
I am writing '\' as the key to a JSON package. The result is something like
"READY_TO_PRINT_DATE":"/\\Date(1403911292:981000+420)\\/"
.
JSON requires the same escaping as you find in JavaScript, and for the same reason... to remove ambiguity from strings. The JSON-version of the string /\\Date(1403911292:981000+420)\\/
is how you would properly represent the actual string /\Date(1403911292:981000+420)\/
.
I hope this helps clears up some of your confusion.
Upvotes: 3