Home > Article > Web Front-end > How Do I Escape Newline Characters in JSON Strings with JavaScript?
Escaping JSON Strings with Newline Characters in JavaScript
In scenarios where your JSON value contains newline characters, it's essential to escape them for proper JSON string formation.
Escaping Newline Characters
To achieve this, use the JSON.stringify() method on your JSON object. Subsequently, utilize the replace() method to substitute all instances of n (the newline character) with \n.
Example:
const jsonString = JSON.stringify({ value: 'This contains a newline\n' }); const escapedString = jsonString.replace(/\n/g, '\n');
Escaping Other Special Characters
Besides newline characters, you may also encounter the need to escape other special characters in JSON strings. However, there are no popular JS libraries specifically designed for escaping all such characters.
Custom Escaping Function
To address this, you can create a custom escape function called escapeSpecialChars() and attach it to the String object's prototype:
String.prototype.escapeSpecialChars = function() { return this.replace(/\n/g, "\n") .replace(/\'/g, "\'") .replace(/\"/g, '\"') .replace(/\&/g, "\&") .replace(/\r/g, "\r") .replace(/\t/g, "\t") .replace(/\b/g, "\b") .replace(/\f/g, "\f"); };
Simplified Code with Custom Function
With the custom function in place, your code becomes:
const jsonString = JSON.stringify({ value: 'This contains a newline\n' }); const escapedString = jsonString.escapeSpecialChars();
This technique caters to escaping both newline characters and other potential special characters in your JSON strings.
The above is the detailed content of How Do I Escape Newline Characters in JSON Strings with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!