Spurious
Spurious

Reputation: 2005

JSON.parse().replace() delivers different result than str.replace()

I am a bit confused by the following code snippet. I would expect the result to be the same:

// # Base for all, used in method 1 directly
const content = `Amazon,💰 bezahlte EUR 75.60 am Amazon
🌈 Heute ausgegeben: EUR 75.60`

// # Base for method 2
const newString = JSON.stringify(content)
const replaceString = newString.replace('\n', ',')

// # Base for method 3
const newReplaceString = content.replace('\n', ',')

// # Output from method 1
console.log(JSON.parse(JSON.stringify(content).replace('\n', ',')));
> "Amazon,💰 bezahlte EUR 75.60 am Amazon
🌈 Heute ausgegeben: EUR 75.60"

// # Output from method 2
console.log(replaceString)
> ""Amazon,💰 bezahlte EUR 75.60 am Amazon\n🌈 Heute ausgegeben: EUR 75.60""

// # Output from method 3
console.log(newReplaceString)
> "Amazon,💰 bezahlte EUR 75.60 am Amazon,🌈 Heute ausgegeben: EUR 75.60"

Why is the replace function on the stringified object not the same? What do I need to do differently?

Upvotes: 0

Views: 240

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

The newline character \n (one character) becomes two characters \ and n, you should be replacing it like so:

const replaceString = newString.replace('\\n', ',');

If you can see the actual character source in the string in the console (i.e. the backslash \ itself followed by whatever character after it) that means that the character is actually broken into two characters.

Upvotes: 3

Related Questions