我需要确定手机号码的前6位是否相同。
最后五个数字可能相同。
但是我需要检查是否只有前6个数字相同
例如,假设有一个手机号码8999999589,那么在任何时候都不应有任何连续的6号。
答案 0 :(得分:1)
首先,获取第一个要比较的数字:
firstNumber = mobileNumberStr[0];
,然后检查以下条件是否正确
mobileNumberStr.substr(0, 6) === firstNumber.repeat(6)
摘要:
如果要使用一种班轮功能:
const isNumberValid = mobileNumber => mobileNumber.substr(0, 6) === mobileNumber[0].repeat(6)
答案 1 :(得分:0)
愚蠢又快速的方法,使用正则表达式:
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));
您甚至可以缩短它:如果您可以替换六个相同的第一个数字,那么它是错误的。
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));
答案 2 :(得分:0)
您可以执行以下操作:
// 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('-------');
};
输出:
+44111111654
6
NOT VALID NUMBER AT INDEX: 0
-------
+44111235646
3
-------
+44222222456
6
NOT VALID NUMBER AT INDEX: 2
-------
+44123456789
1
-------