user1663023
user1663023

Reputation:

Javascript string encoding/decoding

I have some strings like s0 = "\"first line,\\nsecond line,\\n\"", and some other strings like s1 = "first line,\nsecond line,\n", where s0 is like the string representation of the whole s1. I wonder if there's any easy way to convert s0 and s1 both way. I understand I could do replace. However, there might be a whole lot of other escape sequences to take care of.

Upvotes: 0

Views: 52

Answers (1)

charlietfl
charlietfl

Reputation: 171679

You could use JSON methods:

s0 = "\"first line,\\nsecond line,\\n\"",
s1 = "first line,\nsecond line,\n"

console.log('Parse s0 ::', JSON.parse(s0))
console.log('Stringify s1 ::', JSON.stringify(s1))

Upvotes: 3

Related Questions