Home > Software design >  How to use Regex to validate two separate string options
How to use Regex to validate two separate string options

Time:01-05

I'm working on a website feature which is a button component. Currently the button component has Regex set to it so that the url field only accepts a string which has 'https'. This is correct however there is now a new requirement for the button to also accept telephone numbers in the same field.

Initially I just added a separate field to check for a telephone number but this isn't practical, as a user may fill in both fields.

This is the regex syntax to check for a telephone number and below is to check for a website

/tel:\ /

/https/

So ideally I want one field which accepts these two possible inputted patterns.

How do I use Regex to enable this field to check for 'https' and 'tel: ' within the field?

CodePudding user response:

Natasha

The "|" (or) operator can be used to generate a regular expression that matches either "https" or "tel: ". You can specify many choices with this operator, and the regular expression will match if any of the options match

Here is an example:

const regex = /https|tel:\ /;

const input = "https://www.example.com";

if (regex.test(input)) {
  console.log("Input matches the regex!");
} else {
  console.log("Input does not match the regex.");
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

  • Related