Regular expression syntax allows for specifying alternative matches i.e., to match any one of the provided alternatives. For example ‘in|at’ matches either in or at. Alternatives are separated by the pipe (|) character and they are evaluated from left to right until a match is found. The pattern /\t{2}|\s{8}|[-]{11}/ matches either two tabs, 8 spaces or 11 dashes (-). The regex engine first tries to match two tabs failing which it tries to match 8 spaces failing which it tries to match 11 dashes.
Once an alternative is found, further alternatives to the right are ignored even if they could find a longer match. If the regular expression /12|123/ when applied to the input string ‘123’, the resultant match would be ’12’ and not ‘123’ because the alternative 12 is matched first.
let pattern = /12|123/; let targetString = "123";let result = targetString.match(pattern);console.log((result !== null ? `Pattern ${pattern} FOUND in '${targetString}'. Matched string is '${result[0]}'` : `Pattern ${pattern} NOT FOUND in '${targetString}'`));
Output:
Pattern /12|123/ FOUND in '123'. Matched string is '12'