JAVASCRIPT

Extracting Hashtags from Text using Regex

Discover how to efficiently extract all hashtags (e.g., #topic, #example) from a given string in JavaScript using a simple regular expression and `match()`. Ideal for social media apps.

function extractHashtags(text) {
  const hashtagRegex = /#(\w+)/g;
  const matches = text.match(hashtagRegex);
  return matches || []; // Returns an array of hashtags or an empty array if none found
}

const tweet = "Check out this #awesome tutorial on #JavaScript and #regex! #webdev";
const hashtags = extractHashtags(tweet);
console.log(hashtags); // ["#awesome", "#JavaScript", "#regex", "#webdev"]

const noHashtags = "No hashtags here.";
console.log(extractHashtags(noHashtags)); // []
How it works: This JavaScript function `extractHashtags` utilizes a regular expression with the global flag (`g`) to find all occurrences of hashtags within a string. The pattern `#(\w+)` matches a '#' character followed by one or more word characters (letters, numbers, underscores). The `match()` method returns an array containing all matched hashtags, which is useful for tagging, analytics, or categorizing content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs