与 Python 的原始字符串语法 r""(而不是 rf"")等效的 JavaScript 语法是什么?

问题描述 投票:0回答:1

在Javascript中,我们可以使用ES6原始字符串

String.raw`raw text`
来组成原始字符串,但它同时使用了模板字符串语法

如果我想存储字符串

"${a}\\${b}, with \\n"
,我不能使用诸如
String.raw`\${a}\\${b}, with \n`
String.raw"${a}\${b}, with \n"
之类的东西(当然,标签功能不是这样使用的)。

有没有更漂亮的写法,类似于在Python中写

r"{a}\{b}, with \n"
(Python格式语法中没有$)?

javascript syntax rawstring
1个回答
0
投票

我不知道你为什么要避免使用模板字符串。但如果你想要更接近 Python 的语法,你可以使用

Proxy
:

const r = new Proxy({}, {
    get: function(t, p, r) {
        return p.replace(/\\/g, '\\\\')
              .replace(/\n/g, '\\n')
              .replace(/\r/g, '\\r')
              .replace(/\t/g, '\\t')
              .replace(/\v/g, '\\v')
              .replace(/\f/g, '\\f');
    }
})
let result = r["\n\nhaha"]
console.log(result);
let templateRaw = String.raw`\n\nhaha`;
console.log(templateRaw)

Idk,这就是你想要的吗?如果是,请根据您的需要安排

GET
处理程序内的转义

© www.soinside.com 2019 - 2024. All rights reserved.