简体   繁体   English

如何忽略javascript中的转义字符?

[英]How to ignore escape characters in javascript?

I have the following string: 我有以下字符串:

var str = '\x27';

I have no control on it, so I cannot write it as '\\\\x27' for example. 我对此没有控制权,因此无法将其写为“ \\\\ x27”。 Whenever I print it, i get: 每当我打印时,都会得到:

'

since 27 is the apostrophe. 因为27是撇号。 When I call .length on it, it gives me 1. This is of course correct, but how can I treat it like a not escaped string and have it print literally 当我在其上调用.length时,它给了我1。这当然是正确的,但是如何将其视为未转义的字符串并按字面意义进行打印

\x27

and give me a length of 4? 给我4个长度

I'm not sure if you should do what you are trying to do, but this is how it works: 我不确定您是否应该做您想做的事情,但这是这样的:

var s = '\x27';
var sEncoded = '\\x' + s.charCodeAt(0).toString(16);

s is a string that contains one character, the apostrophe. s是包含一个字符(撇号)的字符串。 The character code as a hexadecimal number is 27. 字符代码为十六进制数字是2​​7。

After the assignment var str = '\\x27'; 赋值后var str = '\\x27'; , you can't tell where the contents of str came from. ,您无法确定str的内容来自何处。 There's no way to find out whether a string literal was assigned, or whether the string literal contained an escape sequence. 无法找出是否分配了字符串文字,或者字符串文字是否包含转义序列。 All you have is a string containing a single apostrophe character (Unicode code point U+0027). 您所拥有的只是一个包含单个撇号字符的字符串(Unicode代码点U + 0027)。 The original assignment could have been 最初的任务可能是

var str = '\x27'; // or
var str = "'"; // or
var str = String.fromCodePoint(3 * 13);

There's simply no way to tell. 简直是无话可说。

That said, your question looks like an XY problem . 也就是说,您的问题看起来像XY问题 Why are you trying to print \\x27 in the first place? 您为什么首先尝试打印\\x27

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM