title: Converting textarea value into a valid JSON string
body: <p>I am trying to make sure input from user is converted into a valid JSON string before submitted to server.</p>
  
  <p>What I mean by 'Converting' is escaping characters such as '\n' and '"'.
  Btw, I am taking user input from HTML <code>textarea</code>.</p>
  
  <p>Converting user input to a valid JSON string is very important for me as it will be posted to the server and sent back to client in JSON format. (Invalid JSON string will make whole response invalid)</p>
  
  <p>If User entered </p>
  
  <blockquote>
    <p>Hello New World,<br>
    My Name is "Wonderful".</p>
  </blockquote>
  
  <p>in HTML <code>&lt;textarea&gt;</code>,</p>
  
  <pre><code>var content = $("textarea").val();
  </code></pre>
  
  <p>content will contain new-line character and double quotes character.</p>
  
  <p>It's not a problem for server and database to handle and store data.</p>
  
  <p>My problem occurs when the server sends back the data posted by clients to them in <em>JSON format as they were posted</em>.</p>
  
  <p>Let me clarify it further by giving some example of my server's response.
  It's a JSON response and looks like this</p>
  
  <pre><code>{ "code": 0, "id": 1, "content": "USER_POSTED_CONTENT" }
  </code></pre>
  
  <p>If <code>USER_POSTED_CONTENT</code> contains new-line character '\n', double quotes or any characters that are must be escaped but not escaped, then it is no longer a valid JSON string and client's JavaScript engine cannot parse data.</p>
  
  <p>So I am trying to make sure client is submitting valid JSON string.</p>
  
  <p>This is what I came up with after doing some researches.</p>
  
  <pre><code>String.prototype.escapeForJson = function() {
    return this
      .replace(/\b/g, "")
      .replace(/\f/g, "")
      .replace(/\\/g, "\\")
      .replace(/\"/g, "\\\"")
      .replace(/\t/g, "\\t")
      .replace(/\r/g, "\\r")
      .replace(/\n/g, "\\n")
      .replace(/\u2028/g, "\\u2028")
      .replace(/\u2029/g, "\\u2029");
  };
  </code></pre>
  
  <p>I use this function to escape all the characters that need to be escaped in order to create a valid JSON string.</p>
  
  <pre><code>var content = txt.val().escapeForJson();
  $.ajax(
     ...
     data:{ "content": content }
     ...
  );
  </code></pre>
  
  <p>But then... it seems like <code>str = JSON.stringify(str);</code> does the same job!</p>
  
  <p>However, after reading what <code>JSON.stringify</code> is really for, I am just confused. It says <code>JSON.stringify</code> is to convert JSON Object into string.</p>
  
  <p>I am not really converting JSON Object to string.</p>
  
  <p>So my question is...
  Is it totally ok to use <code>JSON.stringify</code> to convert user input to valid JSON string object??</p>
  
  <p><strong>UPDATES:</strong></p>
  
  <p>JSON.stringify(content) worked good but it added double quotes in the beginning and in the end. And I had to manually remove it for my needs.</p>