← Back to all snippets
JAVASCRIPT

Extract All Hashtags from String

Automatically find and extract all hashtags (e.g., #webdev, #javascript) from text using a powerful JavaScript regex, perfect for social media features.

function extractHashtags(text) {
  const hashtagRegex = /#(\w+)/g;
  const matches = text.match(hashtagRegex);
  return matches ? matches.map(tag => tag.substring(1)) : [];
}

// Example usage:
const post = 'Loving #webdevelopment with #React and #JavaScript today! #frontend #coding';
const hashtags = extractHashtags(post);
console.log(hashtags); // Output: ["webdevelopment", "React", "JavaScript", "frontend", "coding"]

const noHashtags = 'Just plain text.';
console.log(extractHashtags(noHashtags)); // Output: []
How it works: The regex `/#(\w+)/g` searches for a hash symbol `#` followed by one or more word characters (`\w+`). The `g` flag ensures all hashtags are found. The `match()` method returns an array of the full matches (e.g., "#React"). The `map` function then removes the leading `#` from each match to return just the hashtag text without the symbol.

Need help integrating this into your project?

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

Hire DigitalCodeLabs