Last active
September 13, 2021 11:03
-
-
Save umanghome/6d6b45ada126172ee91a1b9f190eb870 to your computer and use it in GitHub Desktop.
Generate HTML for Twitter user bio from API response
This file contains hidden or 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
function setUsernames(description) { | |
return description.replace(/@(\w){1,15}/g, function(username) { | |
return `<a href="https://twitter.com/${username.replace( | |
'@', | |
'' | |
)}" target="_blank">${username}</a>`; | |
}); | |
} | |
function setUrls(description, entities) { | |
const thingsToReplace = entities.description.urls.map( | |
({ display_url, indices, url }) => { | |
return { | |
original: description.slice(indices[0], indices[1]), | |
link: `<a href="${url}" target="_blank">${display_url}</a>`, | |
}; | |
} | |
); | |
let newDescription = description; | |
thingsToReplace.forEach(({ original, link }) => { | |
newDescription = newDescription.replace(original, link); | |
}); | |
return newDescription; | |
} | |
function generateBioHtml(description, entities) { | |
return setUsernames(setUrls(description, entities)); | |
} | |
// Get this from API response | |
const description = | |
'Web aficionado. Amateur drummer. Made https://t.co/Cc7Rq8dzwZ.\nI like maps, JavaScript, CSS, @sveltejs, cities, Web Comics, Tron, @BoJackHorseman, and Oxford commas.'; | |
// Get this from API response | |
const entities = { | |
url: { | |
urls: [ | |
{ | |
url: 'https://t.co/jDjNAVY1qH', | |
expanded_url: 'https://umanggalaiya.in', | |
display_url: 'umanggalaiya.in', | |
indices: [0, 23], | |
}, | |
], | |
}, | |
description: { | |
urls: [ | |
{ | |
url: 'https://t.co/Cc7Rq8dzwZ', | |
expanded_url: 'http://covid19-twitter.in', | |
display_url: 'covid19-twitter.in', | |
indices: [38, 61], | |
}, | |
], | |
}, | |
}; | |
console.log(generateBioHtml(description, entities)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment