将字符串转义为单引号字符串

Escape string as single quoted string

本文关键字:字符串 单引号 转义      更新时间:2023-09-26

我有一个字符串,我想将其编码为单引号Javascript字符串。换句话说,我想要一个函数asSingleQuotedString,这样:

> console.log(asSingleQuotedString("Hello '"friend'" it's me."))
'Hello "friend" it''s me'

我尝试过使用JSON.stringify(),它很有效,但却提供了引号字符串。

这是我当前的解决方案。它的工作原理是转换为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));
}

此方法也适用于任意数据结构,通过使用此正则表达式查找所有引用的字符串:

// Encodes as JSON and converts double quoted strings to single quoted strings
function withSingleQuotedStrings(x) {
    return JSON.stringify(x).replace(/"(?:[^"'']|''.)*"/g, doubleToSingleQuote);
}