HH:MM Time format RegEx inside array [duplicate] - javascript

This question already has answers here:
Regular expression for matching HH:MM time format
(22 answers)
Closed 3 years ago.
I'm using some masked input plugin, which supports mask as the RegEx array. In my case, I want to validate 24h time format (hh:mm). I'm using now RegEx like this:
[/^([0-2])/, /([0-9])/, ':', /[0-5]/, /[0-9]/]
First 2 array elements represents hours
/^([0-2])/, /([0-9])/
Any suggestions how to validate second hour digit? Cause now 25:00 is valid but shouldn't. Need somehow to check first number and if it's 2 - replace [0-9] with [0-3].

Something like this would be more flexible
const arr = ["07:00", "25:05", "23:59", "00:00"];
const valid = arr.filter(t => {
const parts = [hh, mm] = t.split(":");
return !isNaN(hh) && +hh >= 0 && +hh < 24 && !isNaN(mm) && +mm >= 0 && +mm < 60;
});
console.log(valid.length, arr.length, valid.length === arr.length)

Related

Regex for adding thousand separator WITHOUT decimals? [duplicate]

This question already has answers here:
Enhancing regex of thousands separator?
(5 answers)
Closed 10 months ago.
I need a regular expression for adding a dot as a thousand and millon separator in Javascript. I've searched the whole web without finding the format I need.
It would return this:
1
12
123
1.234
12.345
123.456
1.234.567
12.345.678
123.456.789
I'm trying to use it in an input.
handleIdChange = (personalIdNumber) => {
this.validator.updateField("personalId", {
number: personalIdNumber
})
this.props.setVisitorField({
field: "personalId.number",
value: personalIdNumber
});
<CLTextInput
highContrast={true}
onChangeText={this.handleIdChange}
keyboardType="numeric"
placeholder="NĂºmero"
returnKeyType="next"
autoCapitalize="none"
autoCorrect={false}
value={visitor.personalId.number}
error={this.shouldShowError("personalId")}
accessibility
/>
Don't use regular expressions to format numbers. Use a proper number formatter.
If you want german-style number formatting, set that as the locale.
const formatter = new Intl.NumberFormat('de-DE');
for (let i = 0; i < 10; i++) {
const number = 10 ** i;
console.log(formatter.format(number));
}

RegExp check password 6 chars + 1 number [duplicate]

This question already has answers here:
Password REGEX with min 6 chars, at least one letter and one number and may contain special characters
(10 answers)
Closed 5 years ago.
I know this has been asked a million times, but I just can't seem to crack it.
I have this:
function checkPassword(strPassword)
{
var objPattern = new RegExp("^.*(?=.{6,})(?=.*[a-z])[a-z0-9]*$");
var blnResult = objPattern.test(strPassword);
return(blnResult)
}
...but it only seems to check the length, and not if there's a number?
What have I missed?
Edit:
The number can be anywhere in the string, not necessarily at the end.
Keep it simple: if(strPassword.length >= 6 && /\d/.test(strPassword)) will do the work and is way more readable
If you need exactly 6 characters plus 1 number then you can use ^[A-z]{6}[0-9]{1}$ or like atleast 6 characters and atleast 1 number then use ^[A-z]{6,}[0-9]{1,}$
You can just include both tests separately in your function:
function checkPassword(strPassword){
var blnResult = /\w{6,}/.test(strPassword)
&& /\d+/.test(strPassword);
return(blnResult)
}
Demo:
function checkPassword(strPassword){
var blnResult = /\w{6,}/.test(strPassword)
&& /\d+/.test(strPassword);
return(blnResult)
}
var passwords = ["zeaezee2reer", "sds2", "ssdsdsdsdsd", "12155"];
passwords.forEach(function(p){
console.log(p+" ::: "+ checkPassword(p));
});

Convert number to list of three digits in Javascript [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I'm getting large numbers as input and want to display them with a small space for every step of thousand (every 3 digits). So I'm looking for an array of max. three digits as output.
Examples:
Input: 10 Output: [10]
Input: 1234 Output: [1, 234]
Input: 24521280 Output: [23, 521, 280]
It does not matter if the output array contains strings or numbers.
What would be a most elegant (comprehensive / short) solution in Javascript ES6?
I wrote two working solutions, but I feel that they are overly complicated or that I'm missing something:
Solution 1)
function numberToThreeDigitArray(number) {
if (number / 1000 < 1) return [number];
return [
...numberToThreeDigitArray(Math.floor(number / 1000)),
number % 1000
];
}
Solution 2)
function numberToThreeDigitArray(number) {
return number.toString().split('').reverse().map((char, i) => {
return i !== 0 && i % 3 === 0
? ' ' + char
: char;
}).join('').split('').reverse().join('').split(' ');
}
number.toLocaleString().split(',').map(num => +num) should do it for you.
See the toLocaleString MDN docs.
Example:
const arr = (24521280).toLocaleString().split(',').map(num => +num)
// [24, 521, 280]
// or
function getNumber(n) {
return n.toLocaleString().split(',').map(num => +num)
}

javascript regex validate years in range

I have input field for year and I need a regex for validation it.
I have such code: ^([12]\d)?(\d\d)$.
But I want allow to validate only years in certain range (1990-2010, for example). How can I do it?
Edit. range must be 1950-2050
Try this:
1990 - 2010:
/^(199\d|200\d|2010)$/
1950 - 2050:
/^(19[5-9]\d|20[0-4]\d|2050)$/
Other examples:
1945 - 2013:
/^(194[5-9]|19[5-9]\d|200\d|201[0-3])$/
1812 - 3048:
/^(181[2-9]|18[2-9]\d|19\d\d|2\d{3}|30[0-3]\d|304[0-8])$/
Basically, you need to split your range into easy "regexable" chunks:
1812-3048: 1812-1819 + 1820-1899 + 1900-1999 + 2000-2999 + 3000-3039 + 3040-3048
regex: 181[2-9] 18[2-9]\d 19\d\d 2\d{3} 30[0-3]\d 304[0-8]
RegExp does not seem to be the right tool here. If you have the year values already isolated surely a simple comparison would work :
if (+yr >= 1990 && +yr <= 2010)
The +yr converts the string to a number
For a range from 1950 to 2050 you may use the following regex:
^19[5-9]\d|20[0-4]\d|2050$
Online demo
Regex:
/^(19[5-9]\d|20[0-4]\d|2050)$/
Easier...
var year = parseInt(textField.value, 10);
if( year >= 1950 && year <= 2050 ) {
...
}
(199[0-9]|200[0-9]|2010)
This will work in your 'example case'.
Helpful website: http://utilitymill.com/utility/Regex_For_Range
Regex for Current Year(Dynamic) from 1995
var current_year = new Date().getFullYear().toString().split("");
var reg=new RegExp("^(199[5-9]|200[0-9]|[0-"+current_year[0]+"][0-"+current_year[1]+"][0-"+current_year[2]+"][0-"+current_year[3]+"])$");
reg.test("1995");
if you want to check for age between for example 18 or 70 I did it like this.
my solution was
function yearRange(year) {
let now = new Date().getFullYear();
let age = now - Number(year);
if (age < 18 || age > 70) return false;
return true;
}
Here is a regex if you want to find a year in a film name for example.
Years b/n 1900 - 2029 and some symbols are allowed wrapping the year .-_+[(
(?<=(?:\s|\.|_|\-|\+|\(|\[))(?:19[2-9]|20[0-2])\d(?=\s|$|\.|_|\-|\+|\)|\])
check it out here
https://regex101.com/r/eQ9zK7/82
Note you can not start with year, because there is at least interval in front.
In the example first few lines are matching, because we have multiple lines in a single line they wont match.
1917.2019.1080p...
even if 1917 was in range it will mark only 2019

single digit counting using numbers and letters in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a number to the shortest possible character string while retaining uniqueness
I want to count something and I only have a single digit to report the result, so I want to use letters for numbers > 9. E.g.
1 => 1
5 => 5
10 => A
30 => U
55 => u // I may have an off-by-one error here -- you get the idea
>61 => z // 60 will be more than enough, so I'll use z to mean "at least 62"
What's the easiest way to do that using javascript?
Here's one of the many ways to do it:
function num2letter(num) {
if( num > 61) return "z";
if( num < 0) return num;
return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[num];
}
I decided base 36 was good enough:
function oneDigit(n) {
var BASE=36;
if (n >= BASE-1) { n = BASE-1; }
return n.toString(BASE);
}
Another way to do it:
function parse(x)
{
if(x<10)return x;
else if(x<36)return String.fromCharCode(x+55).toUpperCase();
else if(x<62)return String.fromCharCode(x+29).toLowerCase();
else return "z";
}
And this little test:
var res="";
for(var a=-10;a<70;a++)res+=a+" -> "+parse(a)+"\n";
alert(res);
And a fiddle: http://jsfiddle.net/nD59z/4/
And the same way, but with less characters and incomprehensible:
function parse(x)
{
return x<10?x:(x<36?String.fromCharCode(x+55).toUpperCase():(x<62?String.fromCharCode(x+29).toLowerCase():"z"));
}

Categories