[javascript] How to escape a JSON string containing newline characters using JavaScript?

I'm afraid to say that answer given by Alex is rather incorrect, to put it mildly:

  • Some characters Alex tries to escape are not required to be escaped at all (like & and ');
  • \b is not at all the backspace character but rather a word boundary match
  • Characters required to be escaped are not handled.

This function

escape = function (str) {
    // TODO: escape %x75 4HEXDIG ?? chars
    return str
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; };

appears to be a better approximation.