Regex in javascript global catch failed [duplicate] - javascript

This question already has answers here:
regex has no method test [closed]
(3 answers)
Closed 7 years ago.
var r = new RegExp('^[0-9]*$');
function validatePIN (pin) {
//return true or false
if(r.test(pin) && pin.length == 4 || pin.length == 6){
return true;
}else{
return false;
}
}
console.log(validatePin(3627i1));
What's wrong with my regex above? I expect true in this case.

Nothing much is wrong but these conditions will not evaluate correctly:
r.test(pin) && pin.length == 4 || pin.length == 6
As it effectively means (r.test(pin) && pin.length == 4) || pin.length == 6 due to && at higher operator precedence than ||.
You need to enclose conditions in parentheses:
r.test(pin) && (pin.length == 4 || pin.length == 6)
btw you don't even need to check for length afterwards as you can do that in regex itself:
var r = /^[0-9]{4}(?:[0-9]{2})?$/
Now this regex will match either 4 digit number or a six digit number.

validatePin is not the same as validatePIN and 3627i1 is not the same as '3627i1'.
So make sure that you are calling the correct function and passing it a correct argument:
console.log(validatePIN('3627i1'));

syntax errors in your code,
var r = new RegExp('^[0-9]*$');
function validatePIN (pin) {
//return true or false
if(r.test(pin) && pin.length == 4 || pin.length == 6){
return true;
}else{
return false;
}
}
console.log(validatePIN("3627i1")); //call valid function, parameter = string

Related

connect 3 different true statements to an IF ELSE

I want return true if the number is an integer with 4 or 6 digits. no decimals or letter allowed
The thing is not working is the if its really a number check and if its got a decimal.
i think i got already the right functions applied to it but i just cant connect them properly to my if statement.
so i want to check if 3 different things a true then return true but didnt figured out
Please if possible only answer with a hint or a link or SUDO Code or stuff i can look up.
gonna answer the question myself when i figured it out
JS
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if( pin.length === 4 || isNaN(pin) || result) {
return true
} else if ( pin.length === 6 || isNaN(pin) || result) {
return true
} else return false
}
Thanks
A simple regular expression can be used to test that is is 4 or 6 numbers.
function isValidPin (pin) {
return /^(\d{4}|\d{6})$/.test(pin.toString());
}
console.log(isValidPin(123));
console.log(isValidPin("1234"));
console.log(isValidPin("12345"));
console.log(isValidPin("123456"));
console.log(isValidPin("1234567"));
console.log(isValidPin("12.45"));
console.log(isValidPin("12e45"));
You can check the conditions with the AND operator (&&).
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if( pin.length === 4 && isNaN(pin) && result)
{ return true} else if ( pin.length === 6 && isNaN(pin) && result) {
return true
} else return false
}
You need to change your or to and
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if( pin.length === 4 && isNaN(pin) && result)
{ return true}
else if ( pin.length === 6 && isNaN(pin) && result) {
return true
} else return false
}
Ty this:
function validatePIN(pin) {
var parsed = Math.parseInt(pin, 10);
// if it's not an integer
if(pin !== parsed.toString()) return false;
return pin.length === 4 || pin.length === 6;
}
perhaps I'm mistaken - but you could just check if the length is 4 OR 6, and continue your other two checks:
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if(!isNaN(pin) && (pin.length === 4 || pin.length === 6) && result) {
return true
} else return false
}
I've also edited your code, as it seemed illogical returning true for NaN.
I think you want this. You should use regular expression for simplicity.
console.log(445584, validatePin(445584));
console.log("445584", validatePin("445584"));
console.log("alj454", validatePin("alj454"));
console.log(4455.84, validatePin(4455.84));
function validatePin(pin){
return /^(\d{4}|\d{6})$/.test(pin);
}
You might want to look into using isNaN() to detect if there are any characters that aren't numbers.
Also, using .toString() so you can check the .length.

Why does my test pass, even though it doesn't meet my logic gate?

I'm working on telephone validator on FCC. For some reason this passes 5555555555. Why does my logic gate pass this number? For context, this isn't my first attempt at this code. I've added multiple statements, nested if statements, and it still doesn't catch it. Why does this evaluate to true? Here's the code:
function telephoneCheck(str) {
if(str[0] === '1' || '(' && str.length >= 10) {
return true;
}
else {
return false;
}
}
telephoneCheck("5555555555");
You need to restate the condition you're comparing (|| '(' will always be true):
if(str[0] === '1' || str[0] === '(' && str.length >= 10) {
This is due to the fact that && has a greater precedence than the || operator. So without the parenthesis, the '(' && str.length >= 10 part of the expression is evaluated first. So the ultimate condition becomes str[0] === '1' || true which would always be true. So your code would return true for any string of length >= 10

Why does javascript accept a decimal as an integer

I have this html:
<input type='number' id='length' step='0.1' min='0'; max='5'>Length
and this Javascript
num=document.getElementById('length').value;
if(num==1 || 2 || 3 || 4|| 5){
num='0'+num;
}
My problem is this: while I only want the code inside the brackets to execute if the number from the input is an integer, it also activates if it detects 0.8 or some other decimal. Any Idea why? How do I fix it? Thanks.
To make sure num is a whole number, without having to define all possibilities, use:
if (num % 1 == 0)
Why:
num==1 || 2 || 3 || 4|| 5
equals to:
(num==1) || 2 || 3 || 4|| 5
so if num is "1" (always a string type), the expression returns true, otherwise 2 (also a truthy value), eventually your if statement always succeeds.
How to fix:
// implicitly converts the string type into number type before comparison
// returns true if it is an integer-like string
num == Math.floor(num)
So you could do it like this:
if (num == Math.floor(num) && num > 0 && num < 6) {
// an integer-like string that meets the requirement [1, 5]
}
But remember, the num is still string type now. If you want a number, do:
num = +num
You should do
if (num == 1 || num == 2 || num == 3 || num == 4 || num == 5)
WRONG - otherwise it will compare 2 with 2 and says it's true for the 4 last 'if' parameters.
CORRECTO - any number in JS is considered as true.
You have to edit the "If" loop:
if (num == 1 || num == 2 || num == 3 || num == 4 || num == 5)

Javascript multiple or condition check

I have struck with some simple if else checking
var IsCompanyContacttitleUpdate = false;
var ContactStatus = -1;
if ((IsCompanyContacttitleUpdate == false) && (ContactStatus == 2 || 3 || 4))
{
alert('inside if');
}
else if (IsCompanyContacttitleUpdate == false && ContactStatus == 2) {
alert('inside else if');
}
else {
alert('yup yup else');
}
In this case i expected to execute the else part. but its not fired. Please help me to solve this one... Thanks in advance
please see the fiddle
http://jsfiddle.net/vuHYn/1/
This ContactStatus == 2 || 3 || 4 is invalid (maybe invalid is not the correct word, to be more accurate let's say that it's not doing what you think it does)
For your scenario you'll need to use
ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4
Your code could be tranlated to
ContactStatus == 2 || true || true
And this is always true.
the problem is (ContactStatus == 2 || 3 || 4)
the correct way should (ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4)
(ContactStatus == 2 || 3 || 4))
Here is your problem. You are saying if ContactStatus equals 2, it is true, OR true OR true.
False = 0, True is anything not 0.
You need to rewrite that as:
(ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4))
It should work if you change that one thing
Would this work? I changed the if condition from (ContactStatus == 2 || 3 || 4) to ((ContactStatus == 2) || (ContactStatus == 3) || (ContactStatus == 4)).
(ContactStatus == 2 || 3 || 4) evaluates (ContactStatus == 2); since it's true, it evaluates 3 as a condition. Since 3 is different from 0 (zero), then is results as true; and the whole OR evaluates to true. The final result is that the whole if condition is true and the "then" branch is selected.
var IsCompanyContacttitleUpdate = false;
var ContactStatus = 6;
if ((IsCompanyContacttitleUpdate == false) && ((ContactStatus == 2) || (ContactStatus == 3) || (ContactStatus == 4)))
{
alert('inside if')
} else if (IsCompanyContacttitleUpdate == false && ContactStatus == 2) {
alert('inside else if')
} else {
alert('yup yup else');
}

What is the correct syntax for this 'OR' and 'AND' in this 'IF' statement?

I've got an 'if' statement and just wanted to know if these are both valid (which I believe they are) and if so what is the difference?
var type;
var type2;
if ((type == 'BOS'|| type == 'BPS'|| type == 'BRS') && (type2 == 'BOS'|| type2 == 'BPS'|| type2 == 'BRS))
OR
if ((type == 'BOS') || (type == 'BPS') || (type == 'BRS') && (type2 == 'BOS') || (type2 == 'BPS') || (type2 == 'BRS'))
Which has the correct syntax and do they do anything differently? is there a way to shorten this statement?
Thanks
The two statements are different. Yes, they are both valid statements, syntactically, but logically they differ. Since the && operator has a higher precedence than the || in javscript,
the resulting logic will evaluate as follows in statement 2:
1) (type == 'BRS') && (type2 == 'BOS')
2) (type == 'BOS') || (type == 'BPS') || (result of 1) || (type2 == 'BPS') || (type2 == 'BRS')
While in statement 1:
1) (type == 'BOS'|| type == 'BPS'|| type == 'BRS')
2) (type2 == 'BOS'|| type2 == 'BPS'|| type2 == 'BRS')
3) (result of 1) && (result of 2)
var type1;
var type2;
var correct_value = {
BRS: 1,
BOS: 1,
BPS: 1
};
if( correct_value[type1] && correct_value[type2]) {
alert('ok');
}
else {
alert('not ok');
}
Both conditional statement are valid but the result may be different.
The first statement will evaluate the OR value in the first bracket, and then evaluate the OR value in the second bracket, and finally evaluate the AND operator.
The second statement will evaluate the AND first and then evaluate from left to right without specific precedence (as in the first one).
You have to know which one do you actually use to determine the best refactoring code for it.
See this link: Operator Precedence.

Categories