← Back to all snippets
JAVASCRIPT

Extracting Hashtags and Mentions from Text

Learn to easily extract hashtags (#) and mentions (@) from user-generated text using JavaScript regex, perfect for social media features.

const extractSocialTags = (text) => {
  const hashtagRegex = /#(\w+)/g; // Matches # followed by one or more word characters
  const mentionRegex = /@(\w+)/g; // Matches @ followed by one or more word characters

  const hashtags = [...text.matchAll(hashtagRegex)].map(match => match[1]);
  const mentions = [...text.matchAll(mentionRegex)].map(match => match[1]);

  return { hashtags, mentions };
};

const socialText = "Check out this #amazing post by @developer and don't forget to #subscribe!";
const { hashtags, mentions } = extractSocialTags(socialText);
console.log("Hashtags:", hashtags); // ["amazing", "subscribe"]
console.log("Mentions:", mentions); // ["developer"]
How it works: This JavaScript snippet provides a function `extractSocialTags` that uses two distinct regular expressions to find and extract hashtags (strings starting with `#`) and mentions (strings starting with `@`) from a given text. It leverages `matchAll` to find all occurrences and then maps the results to return clean arrays of the extracted tags without their leading symbols.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs