Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Which is the JavaScript RegExp to find any alternative text?
To match any of the specified alternatives in JavaScript, use the alternation operator | within parentheses. This pattern allows you to find multiple possible text options in a single regular expression.
Syntax
(option1|option2|option3)
The pipe symbol | acts as an OR operator, matching any one of the alternatives listed within the parentheses.
Example
Here's how to find alternative text patterns using JavaScript RegExp:
<html>
<head>
<title>JavaScript Regular Expression</title>
</head>
<body>
<script>
var myStr = "one,one,one, two, three, four, four";
var reg = /(one|two|three)/g;
var match = myStr.match(reg);
document.write("Matches found: " + match);
document.write("<br>Number of matches: " + match.length);
</script>
</body>
</html>
Matches found: one,one,one,two,three Number of matches: 5
How It Works
The regular expression /(one|two|three)/g breaks down as follows:
-
(one|two|three)- Matches any of these three words -
gflag - Finds all matches globally, not just the first one
Advanced Example
<html>
<head>
<title>Advanced RegExp Alternatives</title>
</head>
<body>
<script>
var text = "I like cats, dogs, and birds. Fish are also pets.";
var petRegex = /(cat|dog|bird|fish)s?/gi;
var pets = text.match(petRegex);
document.write("Found pets: " + pets.join(", "));
</script>
</body>
</html>
Found pets: cats, dogs, birds, Fish
Key Points
- Use parentheses
()to group alternatives - Separate options with the pipe
|symbol - Add flags like
gfor global matching andifor case-insensitive - The
match()method returns an array of all matches
Conclusion
JavaScript RegExp alternation using (option1|option2|option3) provides an efficient way to search for multiple text patterns simultaneously. This approach is particularly useful for form validation and text processing tasks.
Advertisements
