Javascript 如何在字符串中使用反斜杠 (\)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10041998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use backslashes (\) in a string?
提问by Mik
I tried many ways to get a single backslashfrom an executed(I don't mean an input from html
).
我尝试了很多方法来从执行中获取单个反斜杠(我不是指来自 的输入)。 html
I can get special charactersas tab, new line and many others then escape them to \\t
or \\n
or \\(someother character)
but I cannot get a single backslash when a non-special characteris next to it.
我可以得到特殊字符作为制表符、换行符和许多其他字符,然后将它们转义为\\t
or\\n
或者\\(someother character)
但是当非特殊字符旁边时我无法得到单个反斜杠。
I don't want something like:
我不想要这样的东西:
str = "\apple"; // I want this, to return:
console.log(str); // \apple
and if I try to get character at 0 then I get a
instead of \
.
如果我尝试在 0 处获取字符,那么我得到的a
不是\
.
回答by T.J. Crowder
(See ES2015 update at the end of the answer.)
(请参阅答案末尾的 ES2015 更新。)
You've tagged your question both string
and regex
.
您已将您的问题标记为string
和regex
。
In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \\
.
在 JavaScript 中,反斜杠在字符串文字和正则表达式中都有特殊含义。如果你想在字符串或正则表达式中使用实际的反斜杠,你必须写两个:\\
.
This string starts with onebackslash, the first one you see in the literal is an escape character telling us to take the next character literally:
这个字符串以一个反斜杠开头,你在文字中看到的第一个是一个转义字符,告诉我们从字面上取下一个字符:
var str = "\I have one backslash";
This regular expression will match a singlebackslash (not two); again, the first one you see in the literal is an escape character telling us to take the next character literally:
这个正则表达式匹配一个单个反斜杠(而不是两个); 同样,您在文字中看到的第一个是转义字符,告诉我们从字面上看下一个字符:
var rex = /\/;
If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:
如果您使用字符串来创建正则表达式(而不是像我上面那样使用正则表达式文字),请注意您正在处理两个级别:字符串级别和正则表达式级别。因此,要使用匹配单个反斜杠的字符串创建正则表达式,您最终会使用四个:
// Matches *one* backslash
var rex = new RegExp("\\");
That's because first, you're writing a string literal, but you want to actually put backslashes in it. So you do that with \\
for each one backslash you want. But your regex alsorequires two \\
for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string)
whenver I can; I get confused easily. :-)
那是因为首先,您正在编写一个字符串文字,但您想在其中实际放入反斜杠。所以你\\
对每一个你想要的反斜杠都这样做。但是你的正则表达式也需要两个\\
你想要的真正反斜杠,所以它需要在字符串中看到两个反斜杠。因此,一共有四个。这是我new RegExp(string)
尽可能避免使用的原因之一;我很容易混淆。:-)
ES2015 update
ES2015 更新
Fast-forward to 2015, and as Dolphin_Wood points outthe new ES2015 standard gives us template literals, tag functions, and the String.raw
function:
快进到 2015 年,正如 Dolphin_Wood 指出的,新的 ES2015 标准为我们提供了模板文字、标签函数和String.raw
函数:
// Yes, this unlikely-looking syntax is actually valid ES2015
let str = String.raw`\apple`;
str
ends up having the characters \
, a
, p
, p
, l
, and e
in it. Just be careful there are no ${
in your "string" (template), since this is a template literal and ${
starts a substitution. E.g.:
str
最终包含字符\
, a
, p
, p
, l
, 和e
。请注意${
您的“字符串”(模板)中没有,因为这是一个模板文字并${
开始替换。例如:
let foo = "bar";
let str = String.raw`\apple${foo}`;
...ends up being \applebar
. Also note this isn't quite like "verbatim" strings in C# or similar, as sequences matching the LegacyOctalEscapeSequencein the spec are not allowed and cause a syntax error. So for instance
...最终是\applebar
。另请注意,这不太像C# 中的“逐字”字符串或类似的字符串,因为与规范中的LegacyOctalEscapeSequence匹配的序列是不允许的,并且会导致语法错误。所以例如
// Fails
let str = String.raw`c:\foo\bar`;
...fails because \12
looks like a legacy octal literal.
...失败,因为它\12
看起来像一个传统的八进制文字。
回答by Andy E
\
is an escape character, when followed by a non-special character it doesn't become a literal \
. Instead, you have to double it \\
.
\
是一个转义字符,当后跟一个非特殊字符时,它不会变成一个字面量\
。相反,你必须加倍\\
。
console.log("\apple"); //-> "apple"
console.log("\apple"); //-> "\apple"
There is no way to get the original, raw string definition or create a literal string without escape characters.
无法获得原始的原始字符串定义或创建没有转义字符的文字字符串。
回答by Dolphin_Wood
Try String.raw
method:
尝试String.raw
方法:
str = String.raw`\apple` // "\apple"
Reference here: String.raw()
参考这里:String.raw()