Three ways to expand t.co twitter shortlinks. Copy entire file and run in chrome console to test.
Last active
February 5, 2024 06:21
-
-
Save rnjailamba/8dadf56eabccb7705f6ab5ac0e32cbc4 to your computer and use it in GitHub Desktop.
Expand Twitter Short Links
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
//Helper Function | |
function findFirstUrl(text) { | |
const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g; | |
const match = text.match(urlRegex); | |
return match ? match[0] : null; // Return the first URL or null if none found | |
} | |
//First Way | |
function expandUrl(shortUrl) { | |
return fetch(shortUrl, { method: 'GET' }) | |
.then(response => { | |
return response.text().then((data) => { | |
return data; | |
}).catch((err) => { | |
console.log(err); | |
}) | |
}) | |
} | |
expandUrl('https://t.co/twitter').then((data) => { | |
console.log(findFirstUrl(data)); | |
}); | |
//Second Way | |
async function expandUrl(shortUrl) { | |
const response = await fetch(shortUrl); | |
const data = await response.text(); | |
console.log(findFirstUrl(data)); | |
} | |
expandUrl('https://t.co/twitter'); | |
//Third Way | |
const shortUrls = ['https://t.co/twitter']; | |
const expandedUrls = []; | |
const fetchPromises = shortUrls.map(url => { | |
return fetch(url) | |
.then(response => response.text()) | |
.then(data => { | |
expandedUrls.push(findFirstUrl(data)); | |
}) | |
.catch(error => console.error('Error:', error)); | |
}); | |
Promise.all(fetchPromises) | |
.then(() => console.log(expandedUrls)) | |
.catch(error => console.error('Error:', error)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment