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

3866 views javascript

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


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

Another option - leverage JSON module:

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

posted this

Have an answer?


Please login first before posting an answer.