Escape Json String Containing Newline Characters in JavaScript

In this post, we will see how to escape JSON string containing newline characters using JavaScript.

There is no well known JavaScript library which can escape all special characters in String.

Escape JSON string in JavaScript

There is no direct way to escape JSON String in JavaScript.

You could however chain string's replace() method and replace all special characters using a custom function.

Here is one of way to do it.

You can create a custom function such as escapeSpecialCharsInJSONString() as below:

Let’s see with the help of example.

Output

As you can see, we have successfully escaped new line character and tab character from the JSON String.

Conclusion

To escape JSON string containing newline characters, chain replace() method with all required special characters which you want to escape.

That’s all about how to escape JSON string containing newline characters in JavaScript.

Was this post helpful?

Leave a Reply

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