typescript 打字稿如何转义反斜杠字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33226619/
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
Typescript how to escape backslash character
提问by Bojin Li
I would like to create a regular expression in Typescript to match the decimal separator character followed by a sequence of 0
s in a string. For example, if the decimal separator is .
, then the expression I've come up with is:
我想在 Typescript 中创建一个正则表达式来匹配小数点分隔符后跟0
字符串中的s序列。例如,如果小数点分隔符是.
,那么我想出的表达式是:
/\.0+\b/g
Since the decimal separator is determined at run-time based on locale, I am constructing my expression in code, with the decimalSeperator
as a variable:
由于小数点分隔符是在运行时根据语言环境确定的,因此我在代码中构建了我的表达式,并将其decimalSeperator
作为变量:
"/\" + decimalSeperator + "0+\b/";
My intention is that the double backslash characters will be escaped to a single backslash character.
我的目的是将双反斜杠字符转义为单个反斜杠字符。
However, the double backslash characters are not being escaped in my compiled JavaScript:
但是,双反斜杠字符在我编译的 JavaScript 中没有被转义:
"/\" + decimalSeperator + "0+\b/"
Yet if I used a single backslash, the code won't compile due to the "
being escaped:
然而,如果我使用单个反斜杠,由于"
被转义,代码将无法编译:
"/\" + decimalSeperator + "0+\b/";
- error TS1005: ',' expected.
- error TS1127: Invalid character.
- error TS1002: Unterminated string literal.
- 错误 TS1005: ',' 预期。
- 错误 TS1127:无效字符。
- 错误 TS1002:未终止的字符串文字。
Is this a bug with Typescript or am I doing something wrong?
这是 Typescript 的错误还是我做错了什么?
Thanks
谢谢
回答by basarat
However, the double backslash characters are not being escaped in my compiled JavaScript
但是,双反斜杠字符在我编译的 JavaScript 中没有被转义
That is by intention. The compile time JavaScriptwill be very similar to pre compile TypeScript. "\\"
will compile to "\\"
. However at runtime"\\"
will be \
i.e. a single back slash.
那是故意的。JavaScript的编译时间与预编译 TypeScript 非常相似。"\\"
将编译为"\\"
. 但是在运行时"\\"
将是\
单个反斜杠。
console.log("\"); // prints "\"