Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *