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

Incrementing Variables in JavaScript

JavaScript has three different types of incrementers: i++ ++i and i+=1. Let's look at how they differ from one another.

Apr 06, 2021

WTF is Lodash?

Explore an introduction to Lodash and what it can do to support your JavaScript code.

Apr 21, 2020

Use a Class Map to Set Dynamic Styles

Components often need to use styling based on property combinations. There are a number of ways to solve this, but only one I’ve found to be the cleanest.

Feb 03, 2023