Why is "\ 9" giving "9" and "\ 7" is empty?

I read the lexical grammar of string literals. I found out that both "\9" and "\7" are considered invalid string literals. But why is alert("\9") giving 9 , while alert("\7") empty (I expected \7 )?

+4
source share
2 answers

alert("\7") does not give you an empty string, it gives you a string with character 7. This is because the browser you are testing expands the definition of a string literal to allow escaping of octal characters, as described in Section B.1.2 specifications .

Since 9 not an octal digit, \9 not interpreted as an escape sequence of the octal character, so the backslash is silently discarded.

Please note that in the corresponding implementation, if you were in strict mode, alert("\7") did not work either, as you can see here with Chrome, Firefox or another browser that supports strict mode: Live Copy | A source

 (function() { "use strict"; alert("\7"); // fails })(); 
+4
source

\7 interpreted as an octal string and gives one character with an ASCII value of 7. 9 is not suitable in octal base, so it is interpreted as a regular character. The backslash is silently discarded because it has no side effects.

See also https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals#Using_special_characters_in_strings :

\XXX Latin-1 encoded character, indicated by up to three octal digits XXX between 0 and 377 . For example, \251 is the octal sequence for a copyright symbol.

+3
source

Source: https://habr.com/ru/post/1469183/


All Articles