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
  • g flag - 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 g for global matching and i for 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.

Updated on: 2026-03-15T23:18:59+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements