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

Component-Based JavaScript Architecture

Keep your JavaScript code organized by continuously abstracting it while focusing on patterns within your site's components.

Oct 22, 2018

Compile ES6 Code with Gulp and Babel, Part 4

In the fourth of five parts on compiling multiple ES6 files into a minified bundle, you will learn how to minify your bundle and automatically clean up temporary build files.

Dec 20, 2018

Using jQuery and CoffeeScript in WordPress

The standard ready function doesn't always work in WordPress plugins. Here's a workaround.

May 01, 2013