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

Sometimes, we want to escape a JSON string containing newline characters using JavaScript.

In this article, we’ll look at how to escape a JSON string containing newline characters using JavaScript.

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

To escape a JSON string containing newline characters using JavaScript, we can call string replace to replace various characters.

For instance, we write

const escape = (str) => {
  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");
};

to replace the unescaped characters in the first argument with the escaped characters in the 2nd.

Conclusion

To escape a JSON string containing newline characters using JavaScript, we can call string replace to replace various characters.