You can use RegExp
for that, you don't need to check if two numbers are even, you just need to check two constitutive chars (which is numbers) are even.
so for 1234
you don't have to check 12
and 34
in that case the question could have been more complicated (what will be solved here). you just need to check [1 & 2
], [2 & 3
], [3 & 4
] where none of them are even pairs.
And we can avoid parsing string and read as number, arithmetic calculation for even,.. and such things.
So, for the the simple one (consicutive even chars)
Regex for even digit is : /[02468]/
<your string>.match(/[02468]{2}/)
would give you the result.
Example:
function EvenPairs(str) {
let evensDigit = '[02468]',
consecutiveEvenRegex = new RegExp(evensDigit + "{2}");
return !!str.match(consecutiveEvenRegex);
}
let str1 = "f178svg3k19k46"; //should be true as 4 then 6
let str2 = "7r5gg812"; // should be false, as 8 -> 1 -> 2 (and not 8 then 12)
console.log(`Test EvenPairs for ${str1}: `, EvenPairs(str1));
console.log(`Test EvenPairs for ${str2}: `, EvenPairs(str2));
Now back to the actual (probable) problem to check for 2 constitutive even numbers (not only chars) we just need to check the existence of:
<any even char><empty or 0-9 char><any even char>
i.e. /[02468][0-9]{0,}[02468]/
let's create a working example for it
function EvenPairs(str) {
let evenDigit = '[02468]',
digitsOrEmpty = '[0-9]{0,}',
consecutiveEvenRegex = new RegExp(evenDigit + digitsOrEmpty + evenDigit);
return !!str.match(consecutiveEvenRegex);
}
let str1 = "f178svg3k19k46"; //should be true as 4 then 6
let str2 = "7r5gg812"; // should be true as well, as 8 -> 12
console.log(`Test EvenPairs for ${str1}: `, EvenPairs(str1));
console.log(`Test EvenPairs for ${str2}: `, EvenPairs(str2));