Home > Software design >  Number in range regex
Number in range regex

Time:12-29

Hi i have a string which contains contact number. "xxxxxxxxx". I want to make a regex that checks for number ending in the range 70-79 in javascript. Can anyone please help with regex. I tried but not working.

CodePudding user response:

Try this one. It will match any number ending with 70-79
enter image description here

^[0-9] it will match any number more than one time from the begining
7 is the exact number matching
[0-9]{1}$ means that the last number must be between 0-9 and it should match only once.

CodePudding user response:

Edit: If you do strictly want to have 9 numbers:

let li = ["0123456779", "012345669", "012345670", "012345675", "012345679", "012345680", "690123456", "750123456", "800123456"];
for (i of li) {
  console.log(`${i}: ${i.search(/^\d{7}7\d$/g)}`);
}


Just use $ to specify it is at the end of string

let li = ["abc69", "abc70", "abc75", "abc79", "abc80", "69abc", "70abc", "75abc", "79abc", "80abc"];
for (i of li) {
  console.log(`${i}: ${i.search(/7[0-9]$/g)}`);
}

CodePudding user response:

Instead of regex you can try some thing like this:

let contact_number = "748586544774";
let last_two_digits = contact_number.slice(-2);

if(last_two_digits > 69 && last_two_digits < 80){
    console.log('its working');
}else{
  console.log('Try again');
}

  • Related