Home > Enterprise >  how can I replace double quotation with \" in javascript?
how can I replace double quotation with \" in javascript?

Time:08-28

I wanna check the string and if there is a double quotation first check if the previous character is not backslash, then replace it with \". I used below approach but I didn't know how to check previous character by regex

str = 'field_id   "content" ';
result = str.replace(/\"/g, '\\"');
// result : 'field_id   \"content\"'

str_2 = 'field_id   \"content\" ';
result_2 = str_2.replace(/\"/g, '\\"');

// result_2 : 'field_id   \\"content\\" '
// desired result => 'field_id   \"content\" '

CodePudding user response:

One approach would be to do a regex replacement on all quoted terms, and then build the output using backslash escaped double quotes.

var str = 'field_id   "content" ';
var output = str.replace(/"(.*?)"/g, '\\"$1\\"');
console.log(output);

CodePudding user response:

In your regular expression you escape the " (\"). That's not necessary.

Without it, you get the desired result:

const doubleApoStrophRE = /"/g;
let str = 'field_id   "content" ';
let str2 = 'field_id   \"content\" ';

console.log(str.replace(doubleApoStrophRE, '\\"'));
console.log(str2.replace(doubleApoStrophRE, '\\"'));

// for str3 you need a bit more complexity
let str3 = `field_id   \\\\\\"content\\\\\\"'`;
console.log(str3.replace(/(\\{2,})?"/g, '\\"'));

Check regex101 for trying out regular expressions

  • Related