Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var jsonStr = JSON.stringify(jsonStr); var escapedJSONString = jsonStr .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'); console.log(escapedJSONString); |
You can create a custom function such as escapeSpecialCharsInJSONString() as below:
1 2 3 4 5 6 7 8 9 10 11 12 |
String.prototype.escapeSpecialCharsInJSONString = function() { return this .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'); }; |
Let’s see with the help of example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
String.prototype.escapeSpecialCharsInJSONString = function() { return this .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'); }; const text = '{"name":"John\n", "birth":"14/12/1989\t"}'; const result = text.escapeSpecialCharsInJSONString(); console.log(result); |
Output
1 2 3 |
{\"name\":\"John\n\", \"birth\":\"14\/12\/1989\t\"} |
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.