0

I have a string and it needs to be passed on as a JSON, but then, inside the string, I cannot have " signs, so I was thinking about replacing them with ' signs in my Javascript.

I tried this:

var myString = myString.replace("\"", "\'");

But unfortunately, it only replaced the first occurrence of " in my string. Help?

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
Bocko
  • 33
  • 5
  • 4
    Possible duplicate of [How to replace all occurrences of a string in JavaScript?](http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Kaspar Kjeldsen May 08 '17 at 09:29

5 Answers5

1

You should use a regex to solve the problem.

Hope it helps you.

var myString = 'this "is" a test'
myString = myString.replace(/\"/g, "'");
console.log(myString)
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

use the regular expression, with the flag g to replace

var myString = myString.replace(/\"/g, '\'');
Bender
  • 705
  • 11
  • 25
0

Here split the string with " and join the string with '.

var data = '[{"endDate":"2017-04-22","req":"2017-04-19","nr":2,"type":"CO","startDate":"2017-04-20","Dep":"2017-04-19"},{"endDate":"2017-04-22","req":"2017-04-20","nr":3,"type":"CM","startDate":"2017-04-20","Dep":"2017-04-19"}]';
var result=data.split('"').join("'");
console.log(result);
Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34
0

You can achieve this using the global flag /g. Try this:

var myString=myString.replace(/"/g,"\'");
Rakesh V
  • 146
  • 2
  • 16
0

var s = 'This " is " Just " for test'.replace(/\"/g, "'");
console.log(s);
Zaid Bin Khalid
  • 748
  • 8
  • 25