Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>In js you have to double-escape a dot/character to get an escaped char.</p> </blockquote> <p>You don't get an "escaped char". You get two characters, a backslash and a dot. The dot is not "escaped."</p> <p>The sequence <code>\.</code> is not special in JavaScript string literals. Any escape sequence other than <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4" rel="nofollow">the ones defined by the spec</a> just silently drop the escape character.</p> <p>Your example <code>"\." == "."</code> is <code>true</code> because both literals define the same string, which has <em>one</em> character (a dot). The invalid escape is ignored.</p> <p>Your example <code>"\\." == "."</code> is <code>false</code> because the first literal defines a string with two characters in it (a backslash and a dot), the second defines a string with only one character in it (a dot).</p> <p>How different languages respond to invalid escape sequences varies by language. Some, like JavaScript, just ignore the invalid escape. Others treat an invalid escape sequence as a backslash followed by the next character, e.g., they silently escape the backslash rather than silently dropping the escape.</p> <hr> <p>Re your regex example:</p> <blockquote> <p>In js regexes it works other way around, how weird :)</p> <pre><code>"\.".search(/\./) // no hit &lt;--- Wrong "\\.".search(/\./) // hit </code></pre> </blockquote> <p>That's incorrect, the first one hits as well (the return value for "no match" is <code>-1</code>, not <code>0</code>). The return value of <code>"\.".search(/\./)</code> is <code>0</code> (found a match at index 0, which makes sense, because the <code>.</code> is the first character). The return value of <code>"\\.".search(/\./)</code> is <code>1</code> (found a match at index 1, which makes sense, because the <code>.</code> is the <em>second</em> character).</p> <p>And of course, it's quite correct that you escaped the <code>.</code> in the regular expression literal, because <code>.</code> <strong>is</strong> special in JavaScript regular expressions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload