JAVASCRIPT

Extract Hashtags and User Mentions from Text

Quickly extract all #hashtags and @mentions from social media-like text using efficient JavaScript regular expressions.

function extractSocialEntities(text) {
  const hashtags = [];
  const mentions = [];

  // Regex for hashtags: starts with # followed by word characters
  const hashtagRegex = /#(\w+)/g;
  let hashtagMatch;
  while ((hashtagMatch = hashtagRegex.exec(text)) !== null) {
    hashtags.push(hashtagMatch[1]);
  }

  // Regex for mentions: starts with @ followed by word characters
  const mentionRegex = /@(\w+)/g;
  let mentionMatch;
  while ((mentionMatch = mentionRegex.exec(text)) !== null) {
    mentions.push(mentionMatch[1]);
  }

  return { hashtags, mentions };
}

// Examples
const socialText = "Check out this post from @john_doe about #webdev and #javascript! Also, @jane.smith mentioned it.";
const entities = extractSocialEntities(socialText);
console.log("Hashtags:", entities.hashtags); // ["webdev", "javascript"]
console.log("Mentions:", entities.mentions);   // ["john_doe", "jane"]
How it works: The `extractSocialEntities` function uses two distinct regular expressions to find and extract both hashtags (starting with `#`) and user mentions (starting with `@`) from a given string. It iterates through the text to collect all matching instances, returning an object containing arrays of found hashtags and mentions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs