javascript why double escape dot/character -
in js have double-escape dot/character escaped char. that's weird. why?
js:
"." == "." // true "\." == "." // true "\\." == "." // false "\a" == "a" // true in python/php behaves expected:
"\." == "." // false in js regexes works other way around, how weird :)
"\.".search(/\./) // no hit "\\.".search(/\./) // hit update
like t.j. crowder correctly mentioned regex example wrong. \. regex matches of course literal dot.
the correct example be:
// find literal backslash , literal dot "\\.".search(/\\\./) // position 0 // find literal dot "\\.".search(/\./) // position 1
in js have double-escape dot/character escaped char.
you don't "escaped char". 2 characters, backslash , dot. dot not "escaped."
the sequence \. not special in javascript string literals. escape sequence other the ones defined spec silently drop escape character.
your example "\." == "." true because both literals define same string, has one character (a dot). invalid escape ignored.
your example "\\." == "." false because first literal defines string 2 characters in (a backslash , dot), second defines string 1 character in (a dot).
how different languages respond invalid escape sequences varies language. some, javascript, ignore invalid escape. others treat invalid escape sequence backslash followed next character, e.g., silently escape backslash rather silently dropping escape.
re regex example:
in js regexes works other way around, how weird :)
"\.".search(/\./) // no hit <--- wrong "\\.".search(/\./) // hit
that's incorrect, first 1 hits (the return value "no match" -1, not 0). return value of "\.".search(/\./) 0 (found match @ index 0, makes sense, because . first character). return value of "\\.".search(/\./) 1 (found match @ index 1, makes sense, because . second character).
and of course, it's quite correct escaped . in regular expression literal, because . is special in javascript regular expressions.
Comments
Post a Comment