如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:43:27  来源:igfitidea点击:

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

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, "\"");

http://jsfiddle.net/9b3K3/

http://jsfiddle.net/9b3K3/

回答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 gand all quotes will replaced:

您可以使用带有全局标志的 RegExp,g所有引号都将被替换:

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

回答by sebnukem

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

添加g修饰符: var b = a.replace(/'/g, '"');