Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does javascript regexp (|) pipe operator works same as the (||) logical operator?

I know that the regexp OR (|) operator in javascript matches if one of the sub-strings on both sides of the regexp is matched.

I also know that in JavaScript the logical (||) OR operator checks the second operand only if the first operand is false.

So I want to know if the regexp (|) (also called pipe) OR operator works the same way or it first matches both the sub-strings and then decide the match. If I am not wrong I think it should check the second right hand sub-string only when left hand sub-string is not matched for the sake of performance.

like image 560
me_digvijay Avatar asked Nov 26 '12 06:11

me_digvijay


1 Answers

Yes, | in regular expressions is short circuiting.

For example,

"The | is short circuiting, NOT!".match(/The \| is short circuiting(?:|, NOT!)/)

produces

["The | is short circuiting"]

while

"The | is not short circuiting, NOT!".match(/The \| is not short circuiting(?:, NOT!|)/)

produces

["The | is not short circuiting, NOT!"]

The language specification says

The production Disjunction :: Alternative | Disjunction evaluates as follows:

  1. Evaluate Alternative to obtain a Matcher m1.
  2. Evaluate Disjunction to obtain a Matcher m2.
  3. Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and performs the following:
    a. Call m1(x, c) and let r be its result.
    b. If r isn't failure, return r.
    c. Call m2(x, c) and return its result.

15.10.2.3 line 3b is where the short-circuiting is specified.

like image 104
Mike Samuel Avatar answered Nov 15 '22 01:11

Mike Samuel