Kazuto_Ute
Kazuto_Ute

Reputation: 797

How to unescape JSON stringified textarea value?

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:

  1. When the user types in a special character, JSON.stringify() automatically escapes it.
  2. When the user enters a new line, 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

Answers (2)

Kazuto_Ute
Kazuto_Ute

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

EugenSunic
EugenSunic

Reputation: 13733

You could just remove the new lines:

const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");;

Upvotes: 1

Related Questions