Ask coding questions

← Back to all posts
Interpret String Literal
Coder100 (17111)


Hello, I have a question. Suppose I have a string like this:


Now, when printed, you see:


My question is, how does one replace the escape code for the new line to a literal newline?

function magic(str) {
  // MAGIC
  return str;

magic("hello \\n world"); /* hello 
 world */
magic("h\u0065llo"); // hello (\u0065 is the escape code for e if you haven't realized)

If after a week and nobody answers, I will do it myself.

Clarification: I want escape code sequences too, like the second example (\u0065)

Answered by SpicedSpices (295) [earned 5 cycles]
View Answer
SpicedSpices (295)

What I did for my language in the language jam, is replace all instances of \\n with \n by replace.

let string = 'asdf \\n hjkl'
string = string.replace(/\\n/g, '\n');
SpicedSpices (295)

@Coder100 or for things like \\u0065 you can just use string.replace again such as

let string = 'asdf \\u0065 hjkl'
string = string.replace(/\u/g, 'u');

edit: wait

SpicedSpices (295)

@Coder100 you can try JSON.parse(string) maybe

SpicedSpices (295)

@Coder100 I found a solution:

let str = 'asdf \\u0065 hjkl'
str = JSON.parse('"'+str+'"');

It fixes all of the escaped characters

Coder100 (17111)

k just a sec as i test something before i mark one of your answers @SpicedSpices

Coder100 (17111)

Note for future people: the correct answer is great, but it's javascript only.

This one is more "better" and allows for custom escapes. I hope it finds a use!

Vandesm14 (2644)

You can just use replace(/\n/g, '') to remove the newline character from a string.

Coder100 (17111)

well yeah, but what about the escape sequences (like my e) @Vandesm14

Vandesm14 (2644)

@Coder100 For that, you can do /\u0065/gu

Vandesm14 (2644)

@Coder100 It allows you to use unicode in RegEx

ScOopThe2nd (0)

@Vandesm14 hello i find all your info very helpful

ScOopThe2nd (0)

@Vandesm14 haha just messing around like you do with kids.
fuck you ya big specky baldy!!!