SATYA
SATYA

Reputation: 25

combine regex patterns javascript

I have two regex patterns

1) re1 = /^[0-9\b]+$/ is for allowing only numbers in the input field

2) re2 = /^(7|75|750)$/ is for allowing first 3 numbers of input field to be "750".

Now, I want to combine both the regex patterns where the input field should allow only 750 as first 3 numbers and remaining digits as numbers. I tried following,

const re3 = /^(7|75|750)|0-9\b]+$/

but it is not working.

Thanks in advance.

Upvotes: 0

Views: 231

Answers (3)

Abhishek Kumar
Abhishek Kumar

Reputation: 564

If you want only numbers to be allowed in the input field, then set the input field type as number. It will allow only numbers and you can give re2 regex pattern to check for the first 3 numbers.

function details() {
  const re2 = /^(7|75|750)$/;

  let data = document.getElementById('inputdata').value;
  if (data.match(re2)) {
    alert('Data Valid!')
  } else {
    alert('Data Invalid!')
  }
}
<input type="number" name="" id="inputdata" value=""></input>
<input type="button" name="" value="Check" onclick="details()">

Only e character will be allowed when the type of input field is number because e is an irrational number. I hope it helps.

Upvotes: 0

user1984
user1984

Reputation: 6808

const regex = /^750\d+$/

const tests = [7503944, 343399, 7445, 7503043434];

tests.forEach(el => console.log(el + ": " + regex.test(el)))

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

/^(?:7|75|750)[0-9]*$/

Or,

/^7(?:50?)?[0-9]*$/

Details

  • ^ - start of string
  • 7 - a 7 char
  • (?:50?)? - an optional non-capturing group matching 1 or 0 occurrences (i.e. this is optional) of 5 followed with an optional 0
  • [0-9]* - 0+ digits
  • $ - end of string.

Well, if you need to match the backspace char, add \b into the class, /^7(?:50?)?[0-9\b]*$/.

Upvotes: 1

Related Questions