Convert literal backslash followed by a character to the corresponding escape sequence

3866 views javascript
-3

I have an incoming string that contains a literal backslash followed by n, "\\n". How can I interpret this is a newline, "\n"? Similarly for "\\t" ? "\t". I want to interpret a literal backslash followed by a character as the corresponding escape sequence.

answered question

does this work .replace("\\n", "\n")?

Is there a way to do this without specifying every possible escape sequence?

That's a syntax error since "\" is an unclosed string; the backslash prevents the string from being closed.

2 Answers

8

If you don't want to write out every single replacement, one ugly possibility would be to use eval to interpret the \ followed by the escaped character as a string:

const input = String.raw`foo\nbar\tbaz`;
console.log(input.replace(/\\(.)/g, (_, char) => eval('"\\' + char + '"')));

posted this
13

Another option - leverage JSON module:

const s = 'foo\\nbar\\tbaz';
console.log(JSON.parse('["' + s + '"]')[0]);

posted this

Have an answer?

JD

Please login first before posting an answer.