Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

Regular Expression: Alternation

A Regular Expression (regex) is a sequence of characters that define a pattern that allows you to search, match, locate, replace, manipulate, and manage text. I explained the basics of Regular Expressions in an earlier article: What is a Regular Expression?

Alternation allows allows a match with one or more patterns in a regular expression. The alternate patterns are separated by a pipe character referred to the alternation operator. The syntax for alternation is shown below.

/pattern1|pattern2|pattern3|/

In the example below, the name of one or more programming languages in the sentence is matched and displayed in a message box.

<script>
let strTarget = "The JavaScript programming language is my favorite.";
let regexp = /VBScript|Python|JavaScript/gi;
let res = strTarget.match(regexp);
alert(res);
</script>

The regular expression defines an alternation containing the words VBScript, Python, and JavaScript. Note that the words are separated by a pipe character.

This example displays "JavaScript" in a message box. Try changing the sentence by replacing JavaScript with your favorite programming language.

In the example below, the names of the kinds of pets in the sentence is matched and displayed in a message box.

<script>
let strTarget =  "What kind of pets do you have, cats, dogs, fish or birds.";
let regexp = /cats|dogs|fish|birds/g;
let res = strTarget.match(regexp);
alert(res);
</script>

The regular expression defines an alternation containing the words cats, dogs, fish, and birds. Given the g (global) control character, the alternation regular expression will return, in an array, all the matches it finds to every alternate pattern.

This example displays "cats,dogs,fish,birds" in a message box.

In this article you learned how to create an alternation regular expression that will match alternate patterns in a string.

More Java Script Code:
• Easy Code to Sort a Table by Column
• Learn JavaScript Visually
• Where Did the User Click?
• HTML5 Canvas lineCap and lineJoin Attributes
• Including Special Characters in a JavaScript String
• Easy Picture Zoom Code
• Synchronous and Asynchronous Script Loading
• Calculators for Your Website : Fahrenheit to Celsius Converter
• Regular Expressions Intervals
• Creating Java Script Dynamic or anonymous Functions at Runtime

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro



Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2019 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268