I have this simple code
string = "google windows ico.Win10 ubuntu ico.Microsoft"
keysArray = string.split("+").filter(e => e);
for (let i = 0; i < keysArray.length; i++) {
keysArray[i] = keysArray[i].replace("ico.Win10", '<i class="fab fa-windows"></i>')
keysArray[i] = keysArray[i].replace("ico.Apple", '<i class="fab fa-apple"></i>')
keysArray[i] = keysArray[i].replace("ico.Android", '<i class="fab fa-android"></i>')
keysArray[i] = keysArray[i].replace("ico.Linux", '<i class="fab fa-linux"></i>')
keysArray[i] = keysArray[i].replace("ico.Ubuntu", '<i class="fab fa-ubuntu"></i>')
keysArray[i] = keysArray[i].replace("ico.Unity", '<i class="fab fa-unity"></i>')
keysArray[i] = keysArray[i].replace("ico.Snapchat", '<i class="fab fa-snapchat"></i>')
keysArray[i] = keysArray[i].replace("ico.Whatsapp", '<i class="fab fa-whatsapp"></i>')
keysArray[i] = keysArray[i].replace("ico.Instagram", '<i class="fab fa-instagram"></i>')
keysArray[i] = keysArray[i].replace("ico.Google", '<i class="fab fa-google"></i>')
keysArray[i] = keysArray[i].replace("ico.Microsoft", '<i class="fab fa-microsoft"></i>')
}
console.log(keysArray)
Here I am converting a string to array and filtering all the empty string out. Then replacing the text inside every item of the array if the text exists
But when there are a lot of texts to replace, then I have to call the .replace function thousands of times. Is there a way to do the same thing in a well mannered short way?
I suggest a lookup table
const icons = {
"Win10": "fa-windows",
"Apple": "fa-apple",
"Android": "fa-android",
"Linux": "fa-linux",
"Ubuntu": "fa-ubuntu",
"Unity": "fa-unity",
"Snapchat": "fa-snapchat",
"Whatsapp": "fa-whatsapp",
"Instagram": "fa-instagram",
"Google": "fa-google",
"Microsoft": "fa-microsoft"
}
const string = "google windows ico.Win10 ubuntu ico.Microsoft"
const keysArray = string
.split(" ")
.map(key => key.startsWith('ico.') ? `<i class="fab ${key.replace(key, icons[key.split(".")[1]])}"></i>` : key)
.join(" ");
console.log(keysArray)
If we are ABSOLUTELY SURE on inputs matching the icons, we do not even need that - here the Win10 would fail but the rest work
const string = "google windows ico.Windows ubuntu ico.Microsoft"
const keysArray = string
.split(" ")
.map(key => key.startsWith('ico.') ?
`<i class="fab fa-${key.split(".")[1].toLowerCase()}"></i>` : key)
.join(" ");
console.log(keysArray)