为什么String.raw不能以反斜杠结尾? [英] Why can't String.raw end with a backslash?

查看:150
本文介绍了为什么String.raw不能以反斜杠结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String.raw 可用于创建包含反斜杠的字符串,而不必将这些反斜杠加倍.

String.raw can be used to create a string that contains backslashes, without having to double up those backslashes.

从历史上看,创建字符串时需要将反斜杠加倍:

Historically, you'd need to double up backslashes when creating a string:

let str = "C:\\Program Files\\7-Zip";
console.log(str);

String.raw允许您的代码显示路径而没有双反斜杠:

String.raw allows your code to show the path without doubled backslashes:

let str = String.raw`C:\Program Files\7-Zip`;
console.log(str);

上面的代码可以正常工作,但是今天我发现,如果原始字符串以反斜杠结尾,则它不起作用:

The above code works fine, but today I discovered that it doesn't work if the raw string ends with a backslash:

let str = String.raw`Can't End Raw With Backslash\`;
console.log(str);

上面的代码段会产生此错误:

The above snippet produces this error:

{
  "message": "SyntaxError: `` literal not terminated before end of script",
  "filename": "https://stacksnippets.net/js",
  "lineno": 14,
  "colno": 4
}

为什么这是个例外?

推荐答案

可以,但是请记住,这里有文字"字符和反斜杠字符.您要的是文字反引号.要求输入反斜杠:

It can, but remember that there's the "literal" character and the backslash character. You're asking for a literal backtick. Ask for a literal backslash:

let str = String.raw`...\\`;

紧接反斜杠的任何字符均视为其文字版本,无论它是什么. String.raw可以解决其中一些限制,但不能全部解决.它抑制了\n之类的插值,但不能防止您意外添加文字反引号.

Any character immediately following a backslash is treated as its literal version, regardless of what it is. String.raw can work around some of those limitations, but not all. It suppresses interpolation of things like \n but can't prevent you from accidentally adding a literal backtick.

这篇关于为什么String.raw不能以反斜杠结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆