如何将单个反斜杠放入 ES6 模板文字的输出中?

How do I put a single backslash into an ES6 template literal's output?

我正在努力获取 ES6 模板文字以在其结果中生成单个反斜杠。

> `\s`
's'
> `\s`
'\s'
> `\\s`
'\s'
> `\\s`
'\\s'
> `\u005Cs`
'\s'

通过检查 Node REPL 中的值(而不是使用 console.log 打印它)对 Node 8.9.1 和 10.0.0 进行了测试

如果我答对了你的问题,\怎么样?

我尝试使用 $ node -i 和 运行

console.log(`\`);

成功输出反斜杠。请记住,输出也可能被转义,因此知道您成功获得反斜杠的唯一方法是获取字符代码:

const myBackslash = `\`;
console.log(myBackslash.charCodeAt(0)); // 92

并确保您实际上没有得到 \(即双反斜杠),检查长度:

console.log(myBackslash.length); // 1

这是一个已知问题,unknown string escape sequences 在 JavaScript 普通和模板字符串文字中丢失了转义反斜杠:

When a character in a string literal or regular expression literal is preceded by a backslash, it is interpreted as part of an escape sequence. For example, the escape sequence \n in a string literal corresponds to a single newline character, and not the \ and n characters. However, not all characters change meaning when used in an escape sequence. In this case, the backslash just makes the character appear to mean something else, and the backslash actually has no effect. For example, the escape sequence \k in a string literal just means k. Such superfluous escape sequences are usually benign, and do not change the behavior of the program.

在常规字符串文字中,需要加倍反斜杠以引入文字反斜杠字符:

console.log("\s \s"); // => s \s
console.log('\s \s'); // => s \s
console.log(`\s \s`); // => s \s

有一个更好的主意:使用String.raw:

The static String.raw() method is a tag function of template literals. This is similar to the r prefix in Python, or the @ prefix in C# for string literals. (But it is not identical; see explanations in this issue.) It's used to get the raw string form of template strings, that is, substitutions (e.g. ${foo}) are processed, but escapes (e.g. \n) are not.

因此,您可以简单地使用 String.raw`\s` 来定义 \s 文本:

console.log(String.raw`s \s \s`); // => s \s \s