Home > Back-end >  How to replace '\"' with '\\"' in javascript?
How to replace '\"' with '\\"' in javascript?

Time:01-08

I have a variable str

let str = '{"id": "option2", "text": "\"hello world\""}';

when i try to convert to json using JSON.parse(str);, it throws an error SyntaxError: Expected ',' or '}' after property value in JSON at position 28. I'm aware that the javascript engine reads the str as

{"id": "option2", "text": ""hello world""}, so it's expecting a , or a } after the first set of double quotes ("") that appear before hello world.

Putting an extra backslash allows JSON.parse(str); to run.

let str = '{"id": "option2", "text": "\\"hello world\\""}';

However, I'd like to put the extra backslash programatically. I've tried using the replace method. It doesn't seem to have any effect

let str = '{"id": "option2", "text": "\"hello world\""}'.replace(/\\\"/g, '\\\\\"');

JSON.parse(str) still throws the same error.

The result i'm looking for is such that when str.text is printed on the console, it's value should be "hello world"

CodePudding user response:

This worked for me

But will fail on

{ "someKey" : "" } 

let str = `{"id": "option2", "text": "\"hello world\""}`;
console.log(str)
str = str.split('""').join('"')

console.log(str)
console.log(JSON.parse(str))

CodePudding user response:

the chalenge is that the beginning quoted words are differ from the end. And it seems like javascript has some bugs and doesn't allow to replace "/" using replace function. So only this code works for me

let sourceStr = '{"id": "option2", "text": ""hello world""}';
const searchStr = '""';

const indexes = [...sourceStr.matchAll(new RegExp(searchStr, "gi"))].map(
  (a) => a.index
);
console.log(indexes); // [26,39]

var sourceStrFixed = "";
var index;
for (index = 0; index < indexes.length; index  = 2) {
  sourceStrFixed  =
    sourceStr.substring(0, indexes[index])   '"\\"'
      sourceStr.substring(indexes[index]   2, indexes[index   1])   '\\""';
}
sourceStrFixed  = sourceStr.substring(indexes[index - 1]   2);

String.prototype.replaceAt = function (index, replacement) {
  return (
    this.substring(0, index)  
    replacement  
    this.substring(index   replacement.length)
  );
};
  • Related