lexicore
lexicore

Reputation: 43689

Why does "\054321" produce ",321" in JavaScript?

Just tested in Chrome:

"\054321"

entered in the console gives:

",321"

Clearly "\054" gets converted to ",", but I fail to find a rule for this in the specification.

I am looking for a formal specification for this rule. Why does "\054" produce ","?

Update: It was an OctalEscapeSequence, as defined in B 1.2.

Upvotes: 1

Views: 226

Answers (4)

h2ooooooo
h2ooooooo

Reputation: 39540

If you look at an ascii table you will find that the octal value 054 (decimal: 44) is a comma.

You can find more on the Values, variables, and literals - JavaScript | MDN page that specifies:

Table 2.1 JavaScript special characters

Character   Meaning
XXX           The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.

So essentially, if you use an escape code of 3 digits, it will be evalutated as an octal value.

That said, be aware that octal escapes are deprecated in ES5 (These have been removed from this edition of ECMAScript) and you should use heximal or unicode escape codes instead (\XX or \uXXXX).

If you wish to have the literal string \012345 then simply use a double backslash: \\012345.

Upvotes: 5

Md Ashaduzzaman
Md Ashaduzzaman

Reputation: 4038

The Oct code for , is 054.

Check this Ascii Table

Why you have to put "\" before that Oct code then??

From a quick search you'll find lots of solutions. But this one gave me a better clearification.

Octal escape sequences

Any character with a character code lower than 256 (i.e. any character in the extended ASCII range) can be escaped using its octal-encoded character code, prefixed with . (Note that this is the same range of characters that can be escaped through hexadecimal escapes.) To use the same example, the copyright symbol ('©') has character code 169, which gives 251 in octal notation, so you could write it as '\251'.

[The upper section was collected from an article which is here]

There are also some exceptions which you can find from that article.

Upvotes: 2

Daniel Müller
Daniel Müller

Reputation: 411

"\054" is octal for ",". See here: http://www.asciitable.com/index/asciifull.gif

Upvotes: 0

Álvaro Gómez
Álvaro Gómez

Reputation: 306

Because using \ in a string, as in other languages like C or Python, implies a special character, like \r as carriage return or \n as newline. In this case, It's the ascii value of the coma, which is 054.

Upvotes: 0

Related Questions