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:
null
.http
and https
).www
subdomain.@
symbol within the URL.null
.