Last active
June 2, 2021 12:21
-
-
Save Chizaram-Igolo/0b4940259b0b293fb52c7eb0c7b008e4 to your computer and use it in GitHub Desktop.
A JavaScript event handler that extracts only names and phone numbers from a .VCF file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extractContactDetails(evt, vcfContent) { | |
// An event handler that after having read a .VCF file | |
// proceeds to filter through the contents of that file | |
// extracting only names and phone numbers. | |
evt.preventDefault(); | |
let result = vcfContent; | |
let allContacts = []; | |
let itemsCount; | |
result = result.toLowerCase(); | |
result = result.split("\n"); | |
let contacts_list = []; | |
// We're only interested in names and phone numbers, in VCF, | |
// those lines include "fn:" and "tel" respectively. | |
for (let idx in result) { | |
let text = result[idx]; | |
if (text.includes("fn:")) { | |
text = text.replace("\n", ""); | |
contacts_list = contacts_list.concat(text); | |
} | |
if (text.includes("tel")) { | |
contacts_list = contacts_list.concat(text); | |
} | |
} | |
let contacts_pair_list = []; | |
let line = {}; | |
// Loop through this filtered list removing the unwanted strings | |
// while storing the name, phone number pairs. | |
for (let idx in contacts_list) { | |
let text = contacts_list[idx]; | |
if (text.includes("fn:")) { | |
text = text.replace("fn:", "").replace("\n", ""); | |
line["name"] = text; | |
} else { | |
text = text | |
.replace("tel:", "") | |
.replace("tel;", "") | |
.replace("cell:", "") | |
.replace("cell;", "") | |
.replace("pref:", "") | |
.replace(":", ""); | |
line["phone"] = text; | |
} | |
// Optionally, If the current entry have those 2 items (name and phone number), | |
// add its current date of creation to its object. | |
if (Object.keys(line).length === 2) { | |
line["created"] = new Date().toLocaleDateString("en-GB"); | |
contacts_pair_list.push(line); | |
line = {}; | |
} | |
} | |
// Append this new entries to the existing contacts list | |
allContacts.concat(contacts_pair_list); | |
itemsCount = allContacts.length | |
vcfContent = ""; | |
this.resetFileInput(); | |
return ([allContacts, itemsCount]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment