如何在 JavaScript 中用双引号替换单引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16450250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I replace single quotes with double quotes in JavaScript?
提问by GaneshT
The following code replaces only one single quote:
以下代码仅替换一个单引号:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace("'", "\"");
console.log(b);
回答by RafH
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/'/g, '"');
console.log(b);
Edit: Removed \ as there are useless here.
编辑:删除 \ 因为这里没有用。
回答by RaphaelDDL
Need to use regex for this:
为此需要使用正则表达式:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/\'/g, "\"");
回答by Ted Hopp
You can use a global qualifier (a trailing g
) on a regular expression:
您可以g
在正则表达式上使用全局限定符(尾随):
var b = a.replace(/'/g, '"');
Without the global qualifier, the regex (/'/
) only matches the first instance of '
.
如果没有全局限定符,正则表达式 ( /'/
) 只匹配 的第一个实例'
。
回答by bfavaretto
This looks suspiciously like bad JSON, so I suggest using actual array and object literals, then encoding the proper way:
这看起来很像糟糕的 JSON,所以我建议使用实际的数组和对象文字,然后以正确的方式编码:
var a = [{'column1':'value0','column2':'value1','column3':'value2'}];
var b = JSON.stringify(a);
回答by yckart
You can use a RegExp with the global flag g
and all quotes will replaced:
您可以使用带有全局标志的 RegExp,g
所有引号都将被替换:
var b = a.replace(/'/g, '"');
回答by sebnukem
Add the g
modifier:
var b = a.replace(/'/g, '"');
添加g
修饰符:
var b = a.replace(/'/g, '"');