我有一个字符串,我想将其编码为单引号的Javascript字符串。
换句话说,我想要一个函数asSingleQuotedString
,这样:
> console.log(asSingleQuotedString("Hello \"friend\" it's me."))
'Hello "friend" it\'s me'
我尝试使用JSON.stringify()
,但有效,但提供双引用的字符串。
答案 0 :(得分:0)
这是我目前的解决方案。它的工作原理是转换为JSON格式,取消双引号,转义单引号,然后用单引号替换外部双引号。
// Changes a double quoted string to a single quoted one
function doubleToSingleQuote(x) {
return x.replace(/\\"/g, '"').replace(/\'/g, "\\'").replace(/^"|"$/g, "'");
}
// Encodes a string as a single quoted string
function asSingleQuotedString(x) {
return doubleToSingleQuote(JSON.stringify(x));
}
此方法也适用于任意数据结构,利用this regexp查找所有引用的字符串:
// Encodes as JSON and converts double quoted strings to single quoted strings
function withSingleQuotedStrings(x) {
return JSON.stringify(x).replace(/"(?:[^"\\]|\\.)*"/g, doubleToSingleQuote);
}