Skip to content

Instantly share code, notes, and snippets.

@mbillow
Created May 9, 2024 19:21
Show Gist options
  • Save mbillow/a4637103a2df03a3c5745152aac79c92 to your computer and use it in GitHub Desktop.
Save mbillow/a4637103a2df03a3c5745152aac79c92 to your computer and use it in GitHub Desktop.
JXA Update All Contacts with Country Codes
let formatPhoneNumber = (str) => {
let cleaned = ('' + str).replace(/\D/g, '');
let match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
let intlCode = (match[1] ? '+' + match[1] : '+1')
return [intlCode + ' ', '(', match[2], ') ', match[3], '-', match[4]].join('')
}
return null;
}
app = Application("Contacts");
let allPeople = app.people()
for (let i = 0; i < allPeople.length; i++) {
let person = allPeople[i]
console.log(person.firstName() + " " + person.lastName())
let phoneNumbers = person.phones()
for (let j = 0; j < phoneNumbers.length; j++) {
let currNumber = phoneNumbers[j].value()
let formattedNumber = formatPhoneNumber(currNumber)
if (currNumber != null && formattedNumber != null & currNumber != formattedNumber) {
console.log("changing number from " + currNumber + " to " + formattedNumber)
phoneNumbers[j].value = formattedNumber
}
}
}
app.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment