I am attempting to convert a phone number string into an integer by using parseInt but only receiving the first 3 digits in return and then I would like to add all of the integers of each phone number. Here is my code:
var largest_phone_number = [];
largest_phone_number.push("415-215-2561", "312-367-6721", "345-876-5467");
for(var i=0; i<largest_phone_number.length; i++) {
var number = parseInt(largest_phone_number[i]);
console.log(number);
}
That's because parseInt
will convert up to the first character that's not convertible, hence 3 digits. You could start by stripping out non-numbers with regex first, then do a parseInt
. Don't forget the radix for parseInt
. You wouldn't want to end up with an octal.
var phoneNumbers = largest_phone_number.map(function(number){
return parseInt(number.replace(/[^0-9]/g, ''), 10);
});
// [4152152561, 3123676721, 3458765467]
Some tips for phone numbers:
There are phone numbers whose area code starts with 0
. parseInt
will disregard leading zeroes. Essentially, you just lost information.
There are phone numbers that have these symbols +()-
as well as spaces. They will differ in different parts of the world.
It's best to keep phone numbers as strings. Why? Refer to bullets 1 and 2.