JAVASCRIPT
Extract Hashtags and Mentions from Text
Learn to extract all hashtags (#tag) and mentions (@user) from a string using regular expressions in JavaScript, perfect for social media features.
function extractSocialKeywords(text) {
const hashtagRegex = /#(\w+)/g;
const mentionRegex = /@(\w+)/g;
const hashtags = [...text.matchAll(hashtagRegex)].map(match => match[1]);
const mentions = [...text.matchAll(mentionRegex)].map(match => match[1]);
return { hashtags, mentions };
}
// Examples:
// const post = "Check out this #amazing post by @developer! #webdev";
// const keywords = extractSocialKeywords(post);
// console.log(keywords); // { hashtags: ["amazing", "webdev"], mentions: ["developer"] }
How it works: The `extractSocialKeywords` function processes a given text string to find and extract hashtags (e.g., `#webdev`) and mentions (e.g., `@user`). It uses two separate regular expressions with the global flag (`g`) to find all occurrences: one for `#(\w+)` to capture alphanumeric characters after a hash, and another for `@(\w+)` for mentions. The `matchAll` method is used to get all matches, which are then mapped to extract just the captured group (the tag/user without the prefix), making it ideal for social media content analysis.