Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu May 02, 2024 › #HowTo #Javascript

How to combine two regex in JavaScript?

In this article, we'll delve into combining two regular expressions in JavaScript. We'll explore a straightforward approach using string concatenation with HTML and JavaScript code.

Combining Regex with String Concatenation

To combine two regular expressions in JavaScript, we can use string concatenation to merge their patterns into a single regex pattern string.

Let's consider an example where we want to match email addresses that end with either .com or .org.

<script>
 const regex1 = /\w+@\w+\.(?:com)/;
 const regex2 = /\w+@\w+\.(?:org)/;

 const combinedRegexPattern = `${regex1.source}|${regex2.source}`;
 const combinedRegex = new RegExp(combinedRegexPattern, 'i');

 const email = '3schools.in@gmail.com';
 console.log(combinedRegex.test(email)); // Output: true
</script>

Explanation

  1. Declare two regular expressions regex1 and regex2 to match email addresses ending with .com and .org.
  2. Combine their patterns using string concatenation with the | operator.
  3. Create a new regex object combinedRegex using the combined pattern and specify the i flag for case-insensitive matching.
  4. Test the combined regex pattern against an email address to verify it's working or not.

Example :

<h1>Email Validation</h1>
<input type="text" id="emailInput" placeholder="Enter Your Email">
<button onclick="validateEmail()">Validate</button>
<p id="result"></p>

<script>
 function validateEmail() {
  const emailInput = document.getElementById('emailInput').value;
  const regex1 = /\w+@\w+\.(?:com)/;
  const regex2 = /\w+@\w+\.(?:org)/;
  const combinedRegexPattern = `${regex1.source}|${regex2.source}`;
  const combinedRegex = new RegExp(combinedRegexPattern, 'i');
  const result = combinedRegex.test(emailInput) ? 'Valid email' : 'Invalid email';
  document.getElementById('result').innerText = result;
 }
</script>

Explained

  1. We provide an input field for users to enter an email address.
  2. By clicking the Validate button, the validateEmail() function is called.
  3. Inside this function, we retrieve the email input value and validate it against the combined regex pattern.
  4. The result is displayed below the input field, indicating whether the email is valid or not.
save
listen
AI Answer
Write Your Answer
loading
back
View All