How to use Array.prototype.map() and String.prototype.replace() In Javascript
In this approach, we use Array.prototype.map() to iterate through each character of the JSON string, and String.prototype.replace() to replace double quotes with escaped double quotes, ensuring proper JSON string formatting with backslashes for special characters.
Syntax:
array.map(callback(currentValue, index, array), thisArg)
str.replace(regexp|substr, newSubstr|function)
Example: The below example uses Array.prototype.map() and String.prototype.replace() to add backslash in JSON string JavaScript.
let jStr = `{
"name": "Geek",
"age": 22,
"city": "Delhi"
}`;
let res = Array.from(jStr).map(char => {
if (char === '\\' || char === '"') {
return '\\' + char;
} else {
return char;
}
}).join('');
console.log(res);
Output
{ \"name\": \"Geek\", \"age\": 22, \"city\": \"Delhi\" }
How to Add Backslash in JSON String JavaScript ?
In JavaScript, adding a backslash to a JSON string is important to properly escape special characters, ensuring the integrity and correctness of the JSON format for data processing and storage.
Table of Content
- Using JSON.parse() and JSON.stringify()
- Using for Loop
- Using Array.prototype.map() and String.prototype.replace()