← Back to all snippets
JAVASCRIPT

Extract All Hashtags from Text

A JavaScript function to efficiently find and extract all unique hashtags (e.g., #topic, #jsdev) from a given string, commonly used for social media features.

function extractHashtags(text) {
  // Matches # followed by one or more word characters (alphanumeric + underscore)
  const hashtagRegex = /#(\w+)/g;
  const matches = [...text.matchAll(hashtagRegex)];
  return matches.map(match => match[1]); // Return only the hashtag word without '#'
}

// Example Usage:
const text1 = "Loving #webdev and #JavaScript! Also #regex is cool.";
console.log(extractHashtags(text1)); // ["webdev", "JavaScript", "regex"]

const text2 = "No hashtags here.";
console.log(extractHashtags(text2)); // []
How it works: This JavaScript function `extractHashtags` uses a global regular expression `/^#(\w+)/g` to locate all instances of hashtags within a string. It captures the word following the '#' symbol and returns an

Need help integrating this into your project?

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

Hire DigitalCodeLabs