Created
June 2, 2021 14:34
-
-
Save Chizaram-Igolo/f053d995108fd6b1e126e8af0be361e4 to your computer and use it in GitHub Desktop.
A React 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
handleFile(evt) { | |
// A ReactJS event handle that after having read a .VCF file | |
// procees to filter through the contents of that file | |
// extracting only names and phone numbers. | |
evt.preventDefault(); | |
let result = this.state.vcfContent; | |
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 | |
let clients = [...this.state.allClients]; | |
let combined_clients = clients.concat(contacts_pair_list); | |
console.log(combined_clients); | |
this.setState({ | |
allClients: combined_clients, | |
itemsCount: combined_clients.length, | |
}); | |
this.setState({ vcfContent: "" }); | |
this.resetFileInput(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment