Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve all backslashes in a string

Tags:

javascript

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.

like image 523
mutil Avatar asked May 26 '15 18:05

mutil


Video Answer


2 Answers

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.

like image 73
Erique Bomfim Avatar answered Oct 19 '22 16:10

Erique Bomfim


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 }"
like image 35
Siguza Avatar answered Oct 19 '22 17:10

Siguza