Alternation in JavaScript Regular Expressions (Live Playground)
Alternation in JavaScript regular expressions allows you to match one of several possible patterns within a string. In this tutorial, we'll explore how to use alternation effectively in your regular expressions.
Basic Alternation
To create an alternation, use the pipe symbol |
. This allows you to specify different patterns to match:
const colorPattern = /red|blue|green/; // matches 'red', 'blue', or 'green'
Alternation with Groups
You can use capturing groups ( )
or non-capturing groups (?: )
to combine alternation with other patterns:
const filePattern = /\.(?:jpg|png|gif)$/; // matches a file extension at the end of a string: '.jpg', '.png', or '.gif'
In the example above, the alternation is used inside a non-capturing group to match one or more subdomains in an email address.
Complex Alternation
When using alternation with more complex patterns, it is important to use parentheses to group patterns properly:
const emailPattern = /^[\w._%+-]+@(?:[\w-]+\.)+[A-Za-z]{2,}$/; // matches an email address
Alternation and Escaping Characters
When using alternation with characters that have special meaning in regular expressions, make sure to escape them using a backslash \
:
const mathPattern = /[\+\-*/]|(?:\*\*)/; // matches basic math operators, including the double asterisk for exponentiation
Conclusion
Alternation in JavaScript regular expressions allows you to match one of several possible patterns within a string. We covered basic alternation, alternation with groups, complex alternation, and alternation with escaping characters. Using alternation effectively can help you create versatile and powerful regular expressions for a wide range of pattern-matching tasks.