Regular expression to validate number greater than 0 and less than 1999 - javascript

I need a Regular expression to validate number greater than 0 and less than 1999.
I tried the below code but it require LiveValidation and lot of code.
var f8 = new LiveValidation('f8');
f8.add( Validate.Numericality, { minimum: 0, maximum: 1999} );
Thanks

Have you tried something like this:
^[0-1]?[0-9]{0,3}$

How about
([1-9][0-9]{0,2}|1[0-8][0-9]{2}|19[0-8][0-9]|199[0-8])

Just think how much time you are wasting just by looking for an answer to compare a number with regular expression. But I think as a programmer you know that >< symbols are in every language to compare numbers. I recommend you use those.
function is_valid(strNum){
var num = parseInt(strNum);
return (num>0 && num<1999);
}
This code will do what you need and it'll not even waste time

Check out this pattern:
^([0-9]{0,3}|1\d[0-8][9]|1\d{2}[0-8])$
It will allow values between 1 and 1998, inclusive.

I wouldn't do this with regex but try:
/^(?![2-9].{3})\d{1,4}$/
Again, this in unnecesary, but you get the idea.

Related

Regex for address

With some addresses a building might take up multiple door numbers for example 13 - 15 StreetName.
The "13 - 15" is the part I am focusing on. How would you do a regular expression to pick out this part.
I thought something like [0-9] - [0-9] which works for 1 - 3 but if the address was 12 - 13 [0-9][0-9] - [0-9][0-9] could work but then I want to make sure that something like 13 - 3 wouldnt work as the addresses cannot go backwards and something like 99 - 103 would also work where the numbers are different lengths. Is it really simple and I'm missing something?
I'm still a student and not very good at regular expressions, I just need it for some js I'm doing and have spent far too long getting nowhere.
Thank you.
There's not really a good way to do this since you're effectively trying to parse something that is not a regular language. Referencing something that you've seen before is allowed by several regular expression languages though, but that won't help you in this specific case.
We can easily go for the brute-force solution though :)
https://regex101.com/r/4bRmiL/1
^(\d{3} - \d{3,}|\d{2} - \d{2,}|\d - \d+)$
As you can see though, it still breaks for cases like 5 - 1 which are probably invalid. That's something you need to check outside of the regex.
I don't think this is even possible with regex. I would instead just do something like this:
var addresses = [
"12 - 14 State St.",
"14 - 12 State St.",
];
addresses.forEach(address => console.log(validAddress(address)));
function validAddress(address) {
return !!(address.match(/\d+\s?-\s?\d+/) || []).filter(a => {
var numbers = a.split('-').map(b => b.trim());
return (numbers.length && numbers[0] < numbers[1]);
}).length;
}

How do I reverse an array in JavaScript in 16 characters or less without .reverse()?

I'm trying to solve a challenge on Codewars which requires you to reverse an array in JavaScript, in 16 characters or less. Using .reverse() is not an option.
The maximum number of characters allowed in your code is 28, which includes the function name weirdReverse, so that leaves you with just 16 characters to solve it in. The constraint -
Your code needs to be as short as possible, in fact not longer than 28 characters
Sample input and output -
Input: an array containing data of any types. Ex: [1,2,3,'a','b','c',[]]
Output: [[],'c','b','a',3,2,1]
The starter code given is -
weirdReverse=a=>
My solution (29 characters) is -
weirdReverse=a=>a.sort(()=>1)
which of course fails -
Code length should less or equal to 28 characters.
your code length = 29 - Expected: 'code length <= 28', instead got: 'code length > 28'
I'm not sure what else to truncate here.
Note - I did think about posting this question on CodeGolf SE, but I felt it wouldn't be a good fit there, due to the limited scope.
I'd like to give you a hint, without giving you the answer:
You're close, but you can save characters by not using something you need to add in your code.
By adding the thing you won't use, you can remove ().
Spoiler (answer):
// Note: this only really works for this specific case.
// Never EVER use this in a real-life scenario.
var a = [1,2,3,'a','b','c',[]]
weirdReverse=a=>a.sort(x=>1)
// ^ That's 1 character shorter than ()
console.log(weirdReverse(a))

How do I specify this range using a regular expression in JavaScript?

I need to check if the first 6 digits of a number are from 222100-272099.
This is in JavaScript, and I'm not sure how to go about implementing it.
My initial thought was something like:
match(/^2[2-7][0-9]$/), but I'm not sure how to specify this range correctly.
You shouldn’t really use a RegEx for that. It is better to substring the string and then compare:
const n = Number.parseInt(str.substr(0, 6), 10);
if (222100 <= n && n <= 272099) {
// ...
Regular expressions are for pattern matching in strings:
Wikipedia: Regular expression
You can use JavaScript's parseInt() function to turn your 6 numeric character string into a number that can be used to do a simple greater than/less than check.
W3C: parseInt()

C# string sorting '#' sign difference with Javascript

I faced with a problem that string comparison in C# works a bit strange:
"0".CompareTo("#") // is 1
And I'm very surprised with that because ASCII codes is next:
ASCII '#' // 64
ASCII '0' // 48
If I'm comparing chats or use String.CompareOrdinal everything fine:
'0'>'#' // false
String.CompareOrdinal("0","#") // -16
And in JS it works also as expected:
"0" > "#" // false - in Javascript
Next thing that C# code I can't change - it uses CompareTo.
But I need same sorting rules in Javascript.
I can't find any solution smarter than replace '#' sign with the '#' because it ASCII code less than zero:
ASCII '#' // 35
Maybe somebody can explain why:
"0".CompareTo("#") // is 1
Or suggest better workaround how making comparison the same in Javascript
It's not strange, it's culture specific. I'm not an expert in js but I guess that localeCompare may help you.
CompareTo() will return 1 if the first value is meant to be sorted after the second value (in ascending order), according to its call to String.Compare(firstValue,(String)secondValue, StringComparison.CurrentCulture), which would consider 0 to come after # in a sorted list for display, so you would have #foo, 0foo, 1foo, afoo, Afoo, foo.
In JavaScript, you can pass a function to Array.sort() that would mimic the behavior for the relevant C# culture.

javascript: trying to validate a number that has to be 4 digits to see if x<100 (ie 0100)

i hate asking for help as i would rather figure things for myself, or learn from what others have posted or already asked and solved. as such this is my first post on here!
This is either really really simple and im over complicating things or im going about it the wrong way. ive been searching everywhere for over 2 hours now. im not exactly a noob at js but i am still sort of new,i would say learning, ameteur?? anywho....
what i am trying to do:
so i have a number input box <input type="number" maxlength="4" .../> where a user will enter a 4 digit number (needs to be 4 digits) from 100 to 8000. so obviously 100 to 999 would be 0100 - 0999.
no problem so far, i can just use a string to pass the variable through as 4 digits.
the problem i have is that i need to add certain conditions to validate the input. one condition is bugging me. this is what i have so far:
(var x is already set to the form and number input box)
if (x=="" || isNaN(x) || x.length!== 4 && x< 0100 || x>8000)
{alert(please enter the correct amount!}
else {run rest of function}
so they all work execpt for:x<0100
if the user enters 99 it flags up because it is not 4 digits and if they enter 0099 it accepts it and runs the rest of the function code.
i just need it to alert for any amount from 0001 to 0099.
i found another post, How to make 8 digit number in javascript? , sort of relevant but the guy just wants to output a number padded with zeros. i think one of the solutions (code below) may be of use to me but as i am rather tired, brain frazzled and new i cant solve it:
var i = (100).toPrecision(8).split('.').reverse().join('');
i would start by editing it to:
var i = (x).toPrecision(4).split('.').reverse().join('');
(but would this only work if they typed 99 not 0099...if ya see what i mean)
i think it would be like a reverse of the code (split 0099 to 99.00) , and then the statement would be: if(.... && i<==99 || ....) but idk how to write it in JS...
ok so do ya see how this is messing with me mind, being a semi/quarterly noob and all!!
sorry its not formatted correctly and so long, i havent grasped how to use the code functions...
and thanks for your patience in reading this (if you got this far hehe).
THANKS IN ADVANCE
Slappy-x
The number 0100 will be treated as octal value (which is 64 in decimal).
I think you would do fine by just comparing against strings:
x < "0100" || x > "8000"
Otherwise you have to convert the x into a number and compare it against 100:
+x < 100 || +x > 8000
(actually you don't have to explicitly convert x but it does not hurt either and makes it clearer which data types you are comparing)
Update: And you have to replace && with || as far as I can see.
To check if x is between 0001 and 0099, you can do this
if (x.match(/00([1-9][0-9]|0[1-9])/))
Try a combination of these methods.
You want to check that your number is actually a number first (i.e. doesn't contain letters, etc.). Do this by calling this method to confirm your number is a valid numeric value.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Once confirmed that you're dealing with a number, you can pad it (if necessary) like this:
function pad(num, size) {
var s = "000" + num;
return s.substr(s.length-size);
}
To work with padded numbers, you actually have to convert the value to a string.

Categories