I need to find if the mobile number contain the first 6 digit same or not.
the last five numbers could be the same.
But i need to check if only the first 6 number are same
say for example if have a mobile number, 8999999589 then there should not be any consecutive 6 number at any point.
Dumb and fast way, use regexes :
const falseNumber = '66666655555';
const trueNumber = '12345655555';
const isFalse = function (num) {
const regex = new RegExp('^(' + new Array(10)
.fill(0)
.map((v, i) => new Array(6).join(i))
.join('|') + ')');
return !regex.exec(num);
}
console.log(falseNumber + ' is ' + isFalse(falseNumber));
console.log(trueNumber + ' is ' + isFalse(trueNumber));
You can even shorten it : if you can replace the six same first numbers, then it's false.
const falseNumber = '66666655555';
const trueNumber = '12345655555';
function isFalse(num) {
return num.replace(/^(\d)\1{5}/, '').length !== num.length;
}
console.log(falseNumber + ' is ' + isFalse(falseNumber));
console.log(trueNumber + ' is ' + isFalse(trueNumber));
</div>
You can do something like this:
// Your array of numbers, I supposed you want to understand if
// there are 6 numbers repeated after the international prefix
// if you want something else you can easily edit indexes
const phoneNumbers = [
'+44111111654',
'+44111235646',
'+44222222456',
'+44123456789',
];
// A first cycle where we scan all the numbers in phone numbers
for (let i = 0; i < phoneNumbers.length; i++) {
// we split the number in single chars array
const numbers = phoneNumbers[i].split('');
console.log(phoneNumbers[i]);
let counter = 1;
// A second cycle where we compair the current index element with the previous one
for (let j = 0; j < numbers.length; j++) {
// if the index is between 2 and 9 (+44 ->111111<- 456)
if (j > 2 && j < 9) {
// if the number in current position is equal to the one
// in previous position we increment counter
if (numbers[j] === numbers[j-1]) {
counter++;
}
}
};
console.log(counter);
// if counter is equal to 6, we have an invalid number (as you specified)
if (counter === 6) {
console.log('NOT VALID NUMBER AT INDEX: ', i);
}
console.log('-------');
};
OUTPUT:
+44111111654
6
NOT VALID NUMBER AT INDEX: 0
-------
+44111235646
3
-------
+44222222456
6
NOT VALID NUMBER AT INDEX: 2
-------
+44123456789
1
-------
First, get the first number to compare:
firstNumber = mobileNumberStr[0];
and then check if the following is true
mobileNumberStr.substr(0, 6) === firstNumber.repeat(6)
Summary:
If you want a one liner function:
const isNumberValid = mobileNumber => mobileNumber.substr(0, 6) === mobileNumber[0].repeat(6)