Reputation: 1194
The following code example shows unexpected behavior of replace
method:
let str = "some long string\nwith line\nbreaks"
console.log(str.replace(/\n/g,''))
str = JSON.stringify(str)
console.log(str.replace(/\n/g,''))
I see that there are some warnings about the usage of JSON.stringify
in the documentation and there is a seven-years-old discussion of similar issues here.
What exactly does JSON.stringify
do to the string that the replace does not work the same way?
Upvotes: 1
Views: 1584
Reputation: 79
let str = "some long string\nwith line\nbreaks"
console.log(str.replace(/\n/g,''))
str = JSON.stringify(str).replace(/\\n/g, '');
console.log(str)
The JSON.stringify() method converts a JavaScript object or value to a JSON string. after stringfy the string doesn't contain a newline character (\n), but it make it (\\n). also it add " in start and end of string after stringfy.
To remove those, use .replace(/\\n/g, '') instead of .replace(/\n/g, '')
Upvotes: 0
Reputation: 1075159
It changes the newline characters to the sequence \
n
, because literal newlines are not valid in JSON. So the replace
afterward doesn't find any newlines, because they aren't there anymore.
You can see it by looking at the strings before and after JSON.stringify
:
function hex2(v) {
return "0x" + v.toString(16).padStart(2, "0").toUpperCase();
}
function showCodePoints(label, str) {
console.log(label + ":");
for (const ch of [...str]) {
const lit = ch === "\n" ? "<newline>" : ch === "\\" ? "<backslash>" : ch;
const cp = hex2(ch.codePointAt(0));
console.log(` ${lit.padEnd(12)} (${cp})`);
}
}
let str = "X\nY\nZ";
showCodePoints("before", str);
str = JSON.stringify(str);
showCodePoints("after", str);
.as-console-wrapper {
max-height: 100% !important;
}
Upvotes: 3