Skip to content

Instantly share code, notes, and snippets.

@ekaone
Forked from steven-tey/title-from-url.ts
Created March 28, 2023 07:15
Show Gist options
  • Select an option

  • Save ekaone/a7cfac5fed11a88ba86c325e772782c0 to your computer and use it in GitHub Desktop.

Select an option

Save ekaone/a7cfac5fed11a88ba86c325e772782c0 to your computer and use it in GitHub Desktop.
Get Title from URL
// Note: this gist is a part of this OSS project that I'm currently working on: https://github.com/steven-tey/dub
export default async function getTitleFromUrl (url: string) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 2000); // timeout if it takes longer than 2 seconds
const title = await fetch(url, { signal: controller.signal })
.then((res) => {
clearTimeout(timeoutId);
return res.text();
})
.then((body: string) => {
let match = body.match(/<title>([^<]*)<\/title>/); // regular expression to parse contents of the <title> tag
if (!match || typeof match[1] !== "string") return "No title found"; // if no title found, return "No title found"
return match[1];
})
.catch((err) => {
console.log(err);
return "No title found"; // if there's an error, return "No title found"
});
return title;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment