Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
how can I replace double quotation with \" in javascript?

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\" '
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!