ES6:错误的字符转义序列创建ASCII字符串 [英] ES6: Bad character escape sequence creating ASCII string
问题描述
这是我的代码:
let padded =03;
ascii =`\u00 $ {padded}`;
但是,我收到坏字符转义序列
来自巴别塔我想要结束:
\\\
在 ascii
变量中。我做错了什么?
编辑:
结束语 ascii = eval('\\u00'+ padded +''));
我做错了什么?
unicode转义序列基本上是原子的。你不能真正地构建一个动态的。模板文字基本上执行字符串连接,因此您的代码相当于
'\00'+ padded
现在应该明白为什么你得到这个错误。如果要获取相应的unicode字符,可以使用 String.fromCodePoint
或 String.fromCharCode
:
String.fromCodePoint(3)
如果您希望字符串包含字符序列 \\\
的字符串,那么您只需要转义转义字符即可生成字面反斜杠:
`\\u00 $ {padded}`
/ pre>
Here's my code:
let padded = "03"; ascii = `\u00${padded}`;
However, I receive
Bad character escape sequence
from Babel. I'm trying to end up with:
\u0003
in the
ascii
variable. What am I doing wrong?EDIT:
Ended up with
ascii = (eval('"\\u00' + padded + '"'));
解决方案What am I doing wrong?
A unicode escape sequence is basically atomic. You cannot really build one dynamically. Template literals basically perform string concatenation, so your code is equivalent to
'\00' + padded
It should be obvious now why you get that error. If you want to get the corresponding unicode character you can instead use
String.fromCodePoint
orString.fromCharCode
:String.fromCodePoint(3)
If you want a string that literally contains the character sequence
\u0003
, then you just need to escape the escape character to produce a literal backslash:`\\u00${padded}`
这篇关于ES6:错误的字符转义序列创建ASCII字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!