Brief
If I understand correctly, you want:
- To remove any non-digit characters from the string
- To get numbers that are 11 digits in length (or less)
- To ensure the first and fourth digits in the number are in the range
2-9 (so not 0 or 1)
Code
The first regex can use \D instead of [^\d] as they both mean the exact same thing.
The second part can use any of the following methods (and more, but these are probably some of the simplest methods):
Regex and .length
/^[2-9]\d{2}[2-9]/.test(number) && number.length <= 11
var numbers = [
'(321) 321-4321',
'321.321.4321',
'123.456.7890',
'321.123.4567',
'(321) 321-4321-321'
];
function phoneNumber(number){
number = number.replace(/\D/g, '');
if(/^[2-9]\d{2}[2-9]/.test(number) && number.length <= 11) {
return number;
}
return null;
}
numbers.forEach(function(number){
console.log(phoneNumber(number));
});
charAt, regex and length
!/[01]/.test(number.charAt(0)) && !/[01]/.test(number.charAt(3)) && number.length <= 11
var numbers = [
'(321) 321-4321',
'321.321.4321',
'123.456.7890',
'321.123.4567',
'(321) 321-4321-321'
];
function phoneNumber(number){
number = number.replace(/\D/g, '');
if(!/[01]/.test(number.charAt(0)) && !/[01]/.test(number.charAt(3)) && number.length <= 11) {
return number;
}
return null;
}
numbers.forEach(function(number){
console.log(phoneNumber(number));
});
Regex (alone)
Obviously, you'd change 0 to whatever your minimum digits requirements are (minus 4); so if you want a minimum of 9, you'd put {5,7}.
/^[2-9]\d\d[2-9]\d{0,7}$/.test(number)
var numbers = [
'(321) 321-4321',
'321.321.4321',
'123.456.7890',
'321.123.4567',
'(321) 321-4321-321'
];
function phoneNumber(number){
number = number.replace(/\D/g, '');
if(/^[2-9]\d\d[2-9]\d{0,7}$/.test(number)) {
return number;
}
return null;
}
numbers.forEach(function(number){
console.log(phoneNumber(number));
});
[^\d]is the same as\Dnumber? You know what you have is numeric, check its length and the leading characters.return nullwhen letters or punctuation are present, what exactly do you mean? You existing regex is removing those letters, do you mean that you want to rewrite your expression such that if\Dmatches anything it fails?