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

Dynamically Changing a Netlify Form Name

Netlify forms are easy to use because they are simple in scope. Add a little power with this cool trick.

Mar 31, 2021

ES6 Build Pipeline for Middleman using Gulp

Middleman has abandoned its asset pipeline in favor of a more flexible and customized approach. Let's use this new approach to get ES6 modules into our Middleman project.

Oct 16, 2018

Adding S3 Credentials for Node.js AWS SDK

My go-to method for gaining access to AWS using the Node.js tooling.

Aug 20, 2021