JAVASCRIPT

Extract Hashtags from Text Content

Learn to efficiently extract all hashtags (e.g., #topic) from a given string using a simple yet effective regular expression in JavaScript for social media applications.

function extractHashtags(text) {
  const hashtagRegex = /#(\\w+)/g; // Global flag for all matches
  const matches = [...text.matchAll(hashtagRegex)];
  return matches.map(match => match[1]); // Return just the tag text without '#'
}

// Example usage:
// const text = "This is a #great day for #coding and #learning.";
// console.log(extractHashtags(text)); // ["great", "coding", "learning"]
How it works: This JavaScript function uses a regular expression with a global flag (`g`) to find all occurrences of hashtags in a string. The pattern `/#(\w+)/` captures sequences of word characters immediately following a '#' symbol. `matchAll` is used to get all matches, and then the results are mapped to return just the captured tag text without the leading '#' symbol.

Need help integrating this into your project?

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

Hire DigitalCodeLabs