BallpointBen
BallpointBen

Reputation: 13820

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

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.

Input: "foo\\nbar\\tbaz". Desired output: "foo\nbar\tbaz".

Upvotes: 1

Views: 67

Answers (2)

Ivan Velichko
Ivan Velichko

Reputation: 6709

Another option - leverage JSON module:

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371019

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 + '"')));

Upvotes: 1

Related Questions