Home > Web Front-end > JS Tutorial > How Do I Escape Newline Characters in JSON Strings with JavaScript?

How Do I Escape Newline Characters in JSON Strings with JavaScript?

Linda Hamilton
Release: 2024-11-02 13:03:02
Original
558 people have browsed it

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');
Copy after login

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");
};
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template