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

3 Reasons Why Turbolinks Is Not Worth The Effort

Turbolinks is a great idea in theory, but it comes with enough problems to offset its benefits.

Mar 15, 2016

Compile ES6 Code with Gulp and Babel, Part 3

In the third of five parts on compiling multiple ES6 files into a minified bundle, you will learn how to use a configuration file to build multiple dynamic manifest bundles.

Dec 19, 2018

Export Bear Notes to Markdown Files

Bear is one of the best editors out there, but lacks workflows for your content. Here's how to programmatically write Bear notes to local markdown files.

Jun 16, 2021