Reputation: 797
I have a textarea html element and I want to save its value to a JSON file by stringifying it:
document.querySelector("#button").addEventListener("click", () => {
const rawText = document.querySelector("#textarea").value;
const jsonText = JSON.stringify(rawText);
console.log(jsonText);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<textarea id="textarea" cols="30" rows="10"></textarea>
<button id="button">log json stringified</button>
</body>
</html>
Running the snippet above, we can see two problems:
JSON.stringify()
automatically escapes it.JSON.stringify()
adds a \n
special character.How to format the output such that it preserves any special characters that the user types and ignores new lines entered by the user?
For example when user types in:
one\ntwo\tthree\\nfour
five
I want to log:
"one\ntwo\tthree\\nfourfive"
Instead I am currently logging:
"one\\ntwo\\tthree\\\\nfour\nfive"
Upvotes: 1
Views: 314
Reputation: 797
Expanding from Eugen Sunic's answer, the solution is:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");
const jsonText = JSON.stringify(rawText).replace(/\\\\/g, "\\");
Upvotes: 0
Reputation: 13733
You could just remove the new lines:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");;
Upvotes: 1