I have a string containing backslashes:
"{ \time 4/4 \key c \major d'4 }"
When I try to pass it in a nodejs child_process or just to console.log it, the backslashes are removed:
console.log("{ \time 4/4 \key c \major d'4 }");
// "{ ime 4/4 key c major d'4 }"
I have tried all things I cound find, such as .replace(/\\/g, '\\')
or JSON.stringify
, but nothing seems to work.
The string is constructed dynamically so I can't escape it manually.
Any ideas?
Update after comments:
I am getting this string from a library written in python (python-mingus) using node-python.
As I understand from the answers and the comments, there is no way to parse the string correctly without altering either the library or the wrapper...
Thank you all.
You could use String.raw as alternative to save strings containing slashes; To his you have to put your string between grave sign (`) as follows:
var path = String.raw`your\string\with\slash`;
this way you can preserve slashes.
No, your string does not contain (literal) backslashes.
\
is an escape character, and \t
, \k
and \m
are treated as escape sequences at the time of parsing (and not at the time of printing, as you seem to think). They never even reach your replace
because they aren't there anymore when it runs. Also, for unrecognised sequences (\k
and \m
), the backslash is simply ignored.
The only way to prevent that is to add an additional backslash in the source code:
"{ \\time 4/4 \\key c \\major d'4 }"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With