I'm using match to return only the numbers from the input. I need to limit the number of digits entered to 2. How can I do this?
const numbers = input.match(/[0-9] /g);
CodePudding user response:
Maybe you can use the attribut maxlength="2"
for your imput
CodePudding user response:
We can match on the regex pattern ^[0-9]{1,2}
:
var input = "12345";
const numbers = input.match(/^[0-9]{1,2}/);
console.log(input " => " numbers);
Note that we use ^[0-9]{1,2}
rather than ^[0-9]{2}
because perhaps the user only might enter a single digit.
CodePudding user response:
The simplest way to make it two numbers it to write is as two numbers
const numbers = input.match(/[0-9][0-9]/g);
Snother way is to write it as numbers with count of two
const numbers = input.match(/[0-9]{2}/g);
maybe you need to allow entering 1 number though
const numbers = input.match(/[0-9][0-9]?/g);
const numbers = input.match(/[0-9]|[0-9][0-9]/g);
const numbers = input.match(/[0-9]{1,2}/g);
CodePudding user response:
const input = "1234567890";
const regex = /^\d{2}$/;
const isTwoDigits = regex.test(input);
if (isTwoDigits) {
console.log("The input contains exactly 2 digits");
} else {
console.log("The input does not contain exactly 2 digits");
}
CodePudding user response:
This would be your regex:
const numbers = input.match(/[0-9]{1,2}/);
For simpler writing of regexes, I recommend using https://regex101.com as there is a real time tester and complete cheatsheet with examples.