Skip to content

Instantly share code, notes, and snippets.

@sibljon
Last active November 16, 2019 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sibljon/cf62303360e8fa79c6ef9a7af866ebf4 to your computer and use it in GitHub Desktop.
Save sibljon/cf62303360e8fa79c6ef9a7af866ebf4 to your computer and use it in GitHub Desktop.

The purpose of this is to take JSON data exported from Google Contacts (use a CSV to JSON converter to get it in this format), then properly format US phone numbers. Once done, convert back to CSV and reimport into Google Contacts.

I needed this while traveling.

const exportedGoogleContacts = [...]
const updatedContacts = jonsContacts.map(contact => {
let modifiedContact = {}
Object.keys(contact).forEach(key => {
const value = contact[key]
if (!value) {
return
} else if (String(value).length > 10 && String(value).replace(/[^0-9\+]/g, '').length >= 10 && value.length < 20) {
const formattedPhone = formatNumber(value);
console.log(`converted ${value} to ${formattedPhone}`)
if (!formattedPhone) {
modifiedContact[key] = value
} else {
modifiedContact[key] = formattedPhone
}
} else {
modifiedContact[key] = value
}
})
return modifiedContact
})
console.log(JSON.stringify(updatedContacts))
function formatNumber(number) {
// remove all non-numeric characters except +
number = number.replace(/[^0-9\+]/g, '');
// if there are no numbers
if(number.length < 8) {
return number;
}
// if the number starts with a plus, do nothing
else if(number.charAt(0) == '+') {
return number;
}
// if the number starts with a 1
else if(number.charAt(0) == '1') {
//add plus
number = '+' + number;
return number;
}
else {
number = '+1' + number;
}
return number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment