Open In App

How to Remove Backslash from JSON String in JavaScript?

Removing backslash from JSON String is important because it ensures proper JSON formatting for data interchange and prevents syntax errors during parsing, leading to accurate data representation and processing in JavaScript applications. we will going to learn three different approaches to removing backslash from JSON string in JavaScript.

These are the following approaches:

Using replace() method

In this approach, we are using the replace() method with a regular expression (/\\/g) to globally match and remove all backslashes (\\) in the JSON string jStr, resulting in a cleaned JSON string res without backslashes.

Syntax:

str.replace(regexp|substr, newSubstr|function)

Example: The below example uses the replace() method to remove backslash from JSON string in JavaScript.

let jStr = '{\\"name\\": \\"Geek\\", \\"age\\": 22, \\"city\\": \\"Delhi\\"}';
let res = jStr.replace(/\\/g, '');
console.log(res);

Output
{"name": "Geek", "age": 22, "city": "Delhi"}

Using for Loop

In this approach, we are using a for loop to iterate through each character of the JSON string jStr, appending characters to str only if they are not backslashes (\\), resulting in a cleaned JSON string str that is then parsed and stringified to produce the final result res.

Syntax:

for (initialization; condition; increment/decrement) {
// code
}

Example: The below example uses for Loop to remove the backslash from JSON string in JavaScript.

let jStr = '{\\"name\\": \\"Geek\\", \\"age\\": 22, \\"city\\": \\"Delhi\\"}';
let str = '';
for (let i = 0; i < jStr.length; i++) {
  if (jStr[i] !== '\\') {
    str += jStr[i];
  }
}
let pObj = JSON.parse(str);
let res = JSON.stringify(pObj);
console.log(res);

Output
{"name":"Geek","age":22,"city":"Delhi"}

Using eval() with string replacement

In this approach, we are using eval() with a string replacement (replace() method with /\\/g regular expression) to remove backslashes from the JSON string jStr, then evaluating the cleaned JSON string within parentheses using eval(). This produces a JavaScript object temp, which is stringified to generate the final result res, logging it to the console.

Syntax:

eval(expression)

Example: The below example uses eval() with string replacement to remove backslash from JSON string in JavaScript.

let jStr = '{\\"name\\": \\"Geek\\", \\"age\\": 22}';
let temp = eval(`(${jStr.replace(/\\/g, '')})`);
let res = JSON.stringify(temp);
console.log(res);

Output
{"name":"Geek","age":22}
Article Tags :