Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic vs Direct Octal Character Representation in JavaScript

If I was to create a three digit octal character string the following way:

x = "\\" + a + b + c

Where a is either 0 or 1, and b and c are both a number from 0 to 7, why would alert(x) result in \141 for example, and not a which is alert("\141")?

Second to this, how would you get the original created character code to result in its respective ASCII character?

like image 652
Eliseo D'Annunzio Avatar asked Dec 04 '25 04:12

Eliseo D'Annunzio


2 Answers

Because you're escaping the backslash. Also I'm not sure if JavaScript supports octal encoding, I know it supports hex using \u61 (equivalent hex for octal 141) but if you want to specify it dynamically like that, try using something like this:

// a, b, and c are octal digits

var octal = parseInt('' + a + b + c, 8);

var x = String.fromCharCode(octal);
like image 88
Patrick Roberts Avatar answered Dec 06 '25 16:12

Patrick Roberts


why would alert(x) result in \141 for example, and not a which is alert("\141")?

Because inside a string literal, a \\ and \ are different things. The first creates an actual backslash in the string, whereas in your second example, the backslash introduces an octal escape sequence. It's the same reason \\n in a string literal is a backslash followed by the letter n, but \n is a newline.

Or somewhat more simply: Because you're doing nothing that tries to reinterpret what you've created as a string literal. It's already a string, and nothing tries to evaluate the characters inside it using the string literal rules a second time.

how would you get the original created character code to result in its respective ASCII character

If I'm understanding the question correctly, two ways:

  1. Strip off the \\, convert the remainder of the string to a number via parseInt(..., 8) (octal), and then use String.fromCharCode.

  2. Use eval. But don't do this, do #1


Side note: Octal escape sequences aren't part of standard JavaScript, although in loose mode implementations are allowed, but not required, to support them. They're not allowed in strict mode at all.

like image 22
T.J. Crowder Avatar answered Dec 06 '25 16:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!