RexExp min and max - javascript

I am trying to validate min 1 and max 59 with the following regexp but not working as expected.
^[1-5]?[1-9]$
What is wrong with the expression?

It's work: ^([1-5][0-9]|[1-9])$ (#Tushar)
if (/^([1-5][0-9]|[1-9])$/.test(number)) {
// Successful match
} else {
// Match attempt failed
}
The better/faster way (without regex):
function validate(number) {
number = parseInt(number);
return number > 0 && number < 60;
}
for (var i = 0; i < 65; i++) {
console.log(validate(i));
}
Tested:

Everyone busy trying to provide a solution missed the real question OP asked.
What is wrong with the expression?
Well here is your regex: ^[1-5]?[1-9]$
What you are trying to do is match a number having first digit (optional) in range 1 to 5 and second digit in range 1-9. And since you want to match number from 1 to 59, you will be missing is numbers like 10,20,30,40,50 as pointed out in one comment.

Related

Extending a Variable's Length With Random Numbers Doesn't Work

I am making an AI that tries to solve a user-inputted "numberle" in JavaScript. I don't want the user to do extra work just to see an AI do it's thing, so on the input field, if the user inputs a number that has less than 5 digits, the JavaScript should add random numbers at the end of the variable, until it has a total of five digits.
I used all the loops I had experience with, under an if statement, so if the length of the input was less than 5 (like 3), the loop will add 5 - the number of digits of the input (2) digits that are random, using the Math.random attribute.
Here is the code I currently have:
if (input.length < 5)
do {
input = (input * 10) + Math.floor(Math.random() * 9) + 1;
} while (input.length < 5);
}
console.log(input)
I have also used the for and while loops with basically the same condition (obviously modified for the if loop; made a variable for input.length so that it has the same value).
Here is what I get in the console:
5 // Inputted number (1 digit)
52 // Inputted digit + random number
As you can see, the loop only runs once, although it should've ran 3 more times. I am using strict mode also. My code editor is github.dev, and I am using the CodeSwing console.
If input is a number, it will not have "length", since it is not a string.
You can achieve the desired result like this:
let input = 5;
let digits = 2;
while (input < 10**(digits-1)) input = ~~((input+Math.random())*10);
console.log(input);
Note that ~~ is a compact way of doing Math.floor()
Alternatively, without a while loop:
let input = 5, digits = 2, M = Math; L = x=>~~(M.log(x)/M.log(10))+1;
input = ~~((input+M.random())*10**(digits - L(input)));
console.log(input);

build a regex password 6 letters, 2 digits, and 1 punctuation

I am trying to build a regex that matches for the following
6 letters
digits
1 punctuation
my special characters from my backend to support js special_characters = "[~\!##\$%\^&\*\(\)_\+{}\":;,'\[\]]"
and a minimum of a length of at least 8 or longer.
my password javascript client-side is the following, but however, how can I build a regex with the following data?
if (password === '') {
addErrorTo('password', data['message']['password1']);
} else if(password){
addErrorTo('password', data['message']['password1']);
}else {
removeErrorFrom('password');
}
First check if password.length >= 6
Then I would do it like this:
Set up a letterCount, numCount, puncCount
Loop through the string and earch time you encounter a letter, increase the letterCount (letterCount++), each time you encounter a number increase numCount and so on.
Then validate your password using the counter variables.
This is a good approach because you can tell the user what went wrong. For example, if they only entered 1 number, you can see that from the numCount and tell them specifically that they need at least 2 numbers. You can't do that with just one Regex.
EDIT: Heres the code:
for (let i = 0; i < password.length; i++) {
const currentChar = password[i];
if (checkIfLetter(currentChar)) {
letterCount++;
}
if (checkIfNumber(currentChar)) {
numCount++;
}
if (checkIfPunc(currentChar)) {
puncCount++;
}
}
Then check if the numCount > 2 and so on. I would write the actual regexs but I don't know them myself. It should be pretty easy, just return true if the provided char is a letter for the first function, a number for the second one and so on.
You can use multiple REGEXes to check for each requirement.
let containsAtLeastSixChars = /(\w[^\w]*){6}/.test(password);
let containsAtLeastTwoDigits = /(\d[^\d]*){2}/.test(password);
let containsAtLeastOnePunct = new RegExp(special_characters).test(password);
let isAtLeast8Digits = password.length >= 8;
Then if any of these booleans are false, you can inform the user. A well designed site will show which one is wrong, and display what the user needs to fix.
^(?=.*[0-9]).{2}(?=.*[a-zA-Z]).{6}(?=.*[!##$%^&*(),.?":{}|<>]).{1}$
6Letters, 2digits, and 1 special character.

regex validation for age group

Am looking for a regex validator to validate age between 18 and 65 so far i have this:
^(1[90]|[2-6][0-9])$
I'm not sure why you would want to use regex for checking number ranges.
Below I've got a demo that checks the range the standard way, with greater than and less than but also I've included a regex way.
The regex way requires you to convert the number to a string first which is what the toString() bit is.
const numbers = [1, 20, 55, 67];
for (let num of numbers) {
if (num >= 18 && num <= 65)
console.log(`standard: ${num} is in range`)
}
for (let num of numbers) {
if (num.toString().match(/^([1][8-9]|[2-5][0-9]|[6][0-5])$/))
console.log(`regex: ${num} is in range`)
}
Here is a diagram to explain how the regex works.
^([1][8-9]|[2-5][0-9]|[6][0-5])$
Hope this is helpful.

An algorithm to check if a number is an Extra Perfect Number (it has the same first and last bits) in javascript

This may seem obvious, but what is exactly is an extra perfect number? I need to write an algorithm to find extra perfect for a given n, from 1 thru n. Unfortunately, I can't seem to wrap my mind around the question's wording. These are the examples given:
extraPerfect(3) ==> return {1,3}
extraPerfect(7) ==> return {1,3,5,7}
Task:
Given a positive integer N, return the extra perfect numbers in range from 1 to N.
A number is called Extra Perfect Number if it has the same first and last bits (set bits).
Notes:
Only positive integers will be passed.
The returned vector/list should contain the extra perfect numbers in
ascending order (from lowest to highest).
Example #1
extraPerfect(3) ==> return {1,3}
Explanation:
(1)10 = (1)2
First and last bits as set bits.
(3)10 = (11)2
First and last bits as set bits.
Example #2
extraPerfect(7) ==> return {1,3,5,7}
Explanation:
(5)10 = (101)2
First and last bits as set bits.
(7)10 = (111)2
First and last bits as set bits.
It seems to me that an extra perfect number is simply an odd number as, in base 2, it will always start and end with a 1, whereas an even number will always start with a 1 but end with a 0.
Ah now I see I was wrong because I thought it is all about palindroms. However I hope it can be still helpful. That's the code for palindroms in section between 1 to prompt's value.
var exns = (function(){
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function isEXN(num){
var con = dec2bin(num); // 11011 = 3 + 24 = 27
var accurate = Math.ceil(con.length/2); // 5/2 = 3
var lenmin = con.length-1;
for(var i = 0; i < accurate; i++){
if(con.charAt(i) !== con.charAt(lenmin-i))
return false;
}
return true;
}
var max = parseInt(prompt("Numbers from 1 to ...?"));
var exns = [];
if(!isNaN(max)){
for(var i = 1; i<=max; i++){
if(isEXN(i))
exns.push(i);
}
}
return exns;
})();
Exns should contain array with values.
It looks like extraPerfect should return a list of all numbers less than the argument which have the same first and last digit after converting the decimal argument to binary.
For example:
Decimal - Binary
1 - 1
2 - 10
3 - 11
4 - 100
5 - 101
6 - 110
7 - 111
You'll notice the bold values have the same first and last binary digits.
Some pseudo-code might look like:
function extraPerfect( n ){
var perfects = [];
for(i=0; i<n; i++){
var binary = toBinary(i);
if(binary[0] === binary[binary.length]){
perfects.push(i);
}
}
return perfects;
}
You could pull an algorithm form the pseudo-code.
A Perfect Number is equal to the sum of its positive divisors.
function perfect(num){
for(var i=1,n=0; i<num; i++){
if(num % i === 0){
n += i;
}
}
return n === num;
}
console.log(perfect(6));
console.log(perfect(7));
console.log(perfect(28));
console.log(perfect(8127));
console.log(perfect(8128));

time limit on regular expression in format MM:SS:HH

I need to validate a user input for minutes, seconds, and hundredths in the format MM:SS:HH. However, user's input can not go over 10 minutes. I'm not sure how to limit that and still keep for example 01:01:01 valid.
/^[0-1][0-0]:[0-5][0-9]:[0-9][0-9]$/
This is the expression I had, but my example of 01:01:01 would not have worked.
Brief
I would definitely split the time string on : and then test each part. That's the simplest solution. Alternatively, you can do this relatively easily using regex.
Code
Method 1 - No regex
const str = ["00:00:00", "05:05:05", "10:00:00", "10:00:01", "10:59:59", "20:20:20"];
str.forEach(function(s) {
var a = s.split(":").map(Number);
if(a[0] < 10 || (a[0] === 10 && a[1] === 0 && a[2] === 0)) {
console.log(`Valid: ${s}`);
} else {
console.log(`Invalid: ${s}`);
}
});
Method 2 - Regex
const regex = /^(?:0\d(?::[0-5]\d){2}|10:00:00)$/;
const str = ["00:00:00", "05:05:05", "10:00:00", "10:00:01", "10:59:59", "20:20:20"];
str.forEach(function(s) {
if(regex.exec(s) !== null) {
console.log(`Valid: ${s}`);
} else {
console.log(`Invalid: ${s}`);
}
});
Explanation
I'll only explain the regex in Method 2 as the rest is fairly simple. If you need an explanation about any other parts, however, feel free to ask!
^ Assert position at the start of the line
(?:0\d(?::[0-5]\d){2}|10:00:00) Match either of the following
0\d(?::[0-5]\d){2} Match the following
0 Match this literally
\d Match any digit
(?::[0-5]\d){2} Match the following exactly twice
: Match this literally
[0-5] Match a number in the range between 0 and 5
\d Match any digit
10:00:00 Match this literally
$ Assert position at the end of the line
/(10:00:00|^0[0-9]:[0-5][0-9]:[0-5][0-9]$)/
['10:00:01', '10:00:00', '09:59:59', '05:05:05']
.forEach(t => console.log(t.match(/(10:00:00|^0[0-9]:[0-5][0-9]:[0-5][0-9]$)/)))
Your regex is close. Simply change your regex to:
/^(10:00:00|0[0-9]:[0-5][0-9]:[0-9][0-9])$/

Categories

Resources