Ask coding questions

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

JavaScript

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

"hello\\nworld"

Now, when printed, you see:

hello\nworld

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
Comments
hotnewtop
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');
console.log(string);
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');
console.log(string);

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+'"');
console.log(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.

https://repl.it/@Coder100/FumblingKeenDeals

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!!!