How do I replace single quotes with double quotes in JavaScript?

后端 未结 7 520
遥遥无期
遥遥无期 2021-02-01 02:10

The following code replaces only one single quote:

相关标签:
7条回答
  • 2021-02-01 02:39

    Need to use regex for this:

    var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
    var b = a.replace(/\'/g, "\"");
    

    http://jsfiddle.net/9b3K3/

    0 讨论(0)
  • 2021-02-01 02:43

    Add the g modifier: var b = a.replace(/'/g, '"');

    0 讨论(0)
  • 2021-02-01 02:43

    You can use a RegExp with the global flag g and all quotes will replaced:

    var b = a.replace(/'/g, '"');
    
    0 讨论(0)
  • 2021-02-01 02:50

    You can use a global qualifier (a trailing g) on a regular expression:

    var b = a.replace(/'/g, '"');
    

    Without the global qualifier, the regex (/'/) only matches the first instance of '.

    0 讨论(0)
  • 2021-02-01 02:55

    This looks suspiciously like bad JSON, so I suggest using actual array and object literals, then encoding the proper way:

    var a = [{'column1':'value0','column2':'value1','column3':'value2'}];
    var b = JSON.stringify(a);
    
    0 讨论(0)
  • 2021-02-01 03:03

    var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
    var b = a.replace(/'/g, '"');
    console.log(b);

    Edit: Removed \ as there are useless here.

    0 讨论(0)
提交回复
热议问题