[英]How do I replace single quotes with double quotes in JavaScript?
以下代码仅替换一个单引号:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]"; var b = a.replace("'", "\\""); console.log(b);
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]"; var b = a.replace(/'/g, '"'); console.log(b);
编辑:删除 \\ 因为这里没有用。
为此需要使用正则表达式:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/\'/g, "\"");
您可以在正则表达式上使用全局限定符(尾随g
):
var b = a.replace(/'/g, '"');
如果没有全局限定符,正则表达式 ( /'/
) 只匹配'
的第一个实例。
replaceAll(search, replaceWith)
替换所有出现的search
与replaceWith
。
然后,通过用不同类型包装一种类型的 qoutes 来确保你有一个字符串:
"a 'b' c".replaceAll("'", '"')
// result: "a "b" c"
"a 'b' c".replaceAll(`'`, `"`)
// result: "a "b" c"
replaceAll ( MDN ): replaceAll(search, replaceWith)
它实际上与将replace()
与全局正则表达式 (* replace()
一起使用相同,只是在我看来, replaceAll()
更具可读性。
(*) 意味着它将匹配所有出现。
示例 1 - 使用字符串搜索
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
console.log(p.replaceAll('2020', '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
示例 2 - 使用正则表达式搜索
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
const regex = /2020/gi
console.log(p.replaceAll(regex, '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
重要( ! )如果您选择正则表达式:
使用正则
regexp
您必须设置全局 ("g") 标志; 否则,它会抛出一个 TypeError:“replaceAll 必须用全局 RegExp 调用”。
您还可以使用函数作为replaceWith
在这种情况下,将在执行匹配后调用该函数。 函数的结果(返回值)将用作替换字符串。
这看起来很像糟糕的 JSON,所以我建议使用实际的数组和对象文字,然后以正确的方式编码:
var a = [{'column1':'value0','column2':'value1','column3':'value2'}];
var b = JSON.stringify(a);
添加g
修饰符: var b = a.replace(/'/g, '"');
您可以使用带有全局标志g
的 RegExp 并且所有引号都将被替换:
var b = a.replace(/'/g, '"');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.