简体   繁体   中英

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. Whenever I print it, i get:

'

since 27 is the apostrophe. 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

\x27

and give me a length of 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. The character code as a hexadecimal number is 27.

After the assignment var str = '\\x27'; , you can't tell where the contents of str came from. 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). 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 . Why are you trying to print \\x27 in the first place?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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