Home

Extract Twitter Handle from URL with JavaScript

Code snippet that extracts a Twitter user handle from a valid Twitter URL using JavaScript.

Here’s a quick JavaScript function that will find the Twitter handle from within a Twitter URL and return the handle with the preceding @ symbol:

function extractTwitterHandle(url) {
if (!url) return null;
const match = url.match(/^https?:\/\/(www\.)?twitter.com\/@?(?<handle>\w+)/);
return match?.groups?.handle ? `@${match.groups.handle}` : null;
}

Notice here that we’re accounting for the following conditions:

  • If there is no URL passed, return null.
  • Insecure URLs (http and https).
  • Including or omitting the www subdomain.
  • Including or omitting the @ symbol within the URL.
  • If the URL was present but invalid, or if the handle couldn’t be found, return null.

Let's Connect

Keep Reading

The Right Way to Learn JavaScript in 2020

At first glance, the JavaScript ecosystem is overwhelming. Here are thoughts on how to slow down, center yourself, and find a place to begin.

Aug 20, 2020

Use Netlify to Host JavaScript Libraries

Netlify is built to host websites, but it can be a handy resource for JavaScript libraries, too.

Nov 30, 2018

Abstract hard-coded values in your code

When JS frameworks don’t bring low-level structure recommendations on constants, configuration, and content, you’ll benefit from establishing your own conventions.

May 01, 2025