← Back to all snippets
JAVASCRIPT

Extract Hashtags from Text String

Discover how to efficiently extract all hashtags from a given text string using a regular expression in JavaScript, perfect for social media features.

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

// Example usage:
// console.log(extractHashtags("This is a #test with multiple #hashtags and #anotherone.")); // ["test", "hashtags", "anotherone"]
// console.log(extractHashtags("No hashtags here.")); // []
How it works: The `extractHashtags` function uses a global regular expression `/ #(\w+)/g` to find all occurrences of words prefixed with "#". It captures the word itself (excluding the "#") and returns an array of these extracted hashtags, making it useful for parsing social media content or indexing topics.

Need help integrating this into your project?

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

Hire DigitalCodeLabs