Home > other >  Convert an escaped backslash to be an escaping backslash
Convert an escaped backslash to be an escaping backslash

Time:07-25

I have a string from the server that the backslash are escaped:

const s = 'text\\n'

Because the backslashes are escaped, the backslash that is supposed to escape the new line is ignored. So my string doesn't have a new line as it should.

I would like to have my variable s to contain: text\n

I test this using length property:

'text\\n'.length === 6;  // this is wrong
'text\n'.length === 5;   // this is correct

How do I convert the wrong string to be the correct string?

CodePudding user response:

'text\\n'.replaceAll('\\n', '\n')

CodePudding user response:

If all of your backslashes are escaped, you can just replace all of two backslashes \\ with one backslash \ to revert the string to its original form

const s = 'text\\n';
const regex = /\\/g;
console.log(s.replaceAll(regex, '\\')); // note that the 2nd arg is '\\', this is for escaping the '\' character
// return "text\n"

  • Related