Reputation: 13820
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
Reputation: 6709
Another option - leverage JSON module:
const s = 'foo\\nbar\\tbaz';
console.log(JSON.parse('["' + s + '"]')[0]);
Upvotes: 0
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