How to Extract a Twitter Username from a String in JavaScript?

Estimated read time 1 min read

To extract a Twitter username (also known as a Twitter handle) from a string in JavaScript, you can use a regular expression. Here’s an example:

const string = "Hey @johndoe, what's up?";
const usernameRegex = /@([A-Za-z0-9_]{1,15})/g;
const usernames = string.match(usernameRegex);
console.log(usernames); // Output: ["@johndoe"]

Here’s what the regular expression does:

  • @ – matches the “@” symbol
  • ([A-Za-z0-9_]{1,15}) – matches the username, which can be between 1 and 15 characters long and can include letters, numbers, and underscores.

The g flag at the end of the regular expression enables a global search, which means it will find all occurrences of usernames in the string.

The string.match(usernameRegex) method returns an array of all matches. In this case, it will return an array with a single element that contains the Twitter username.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply