Tastror
Tastror

Reputation: 11

What is the equivalent JavaScript syntax to Python's rawstring syntax r"" (instead of rf"")?

In Javascript, we can use the ES6 raw string String.raw`raw text` to form a raw string, but it uses the template string syntax at the same time.

If I want to store the string "${a}\\${b}, with \\n", I cannot use something such as String.raw`\${a}\\${b}, with \n` or String.raw"${a}\${b}, with \n" (of course, the tag function is not used this way).

Is there a prettier way to write it, similar to writing r"{a}\{b}, with \n" (no $ in Python format syntax) in Python?

Upvotes: 1

Views: 82

Answers (1)

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6501

I do not know why you want to avoid template strings. But if you want a closer syntax to Python, you can use a Proxy:

const r = new Proxy({}, {
    get: function(t, p, r) {
        return p /*.replace(/\\/g, '\\\\') optional*/
              .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)

console.log(String.raw`{a}\{b}, with \n`)
console.log(r["{a}\\{b}, with \n"]) // here you have to escape the backlash

Idk, is that what you want? If yes, arrange the escapes inside the GET handler to your needs

Upvotes: 1

Related Questions