Reputation: 58863
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?
Upvotes: 1
Views: 3235
Reputation: 33618
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?
Upvotes: 0
Reputation: 11297
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.
Upvotes: 1