JAVASCRIPT

Extract All Hashtags from Text using Regex in JavaScript

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

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

// Examples:
// const text1 = "This is a #test post with multiple #hashtags.";
// console.log(extractHashtags(text1)); // ["test", "hashtags"]

// const text2 = "No hashtags here.";
// console.log(extractHashtags(text2)); // []
How it works: This JavaScript function uses a regular expression with the global flag (`g`) to find all occurrences of hashtags in a given string. The pattern `/#(\w+)/` captures words immediately following a '#' symbol. The `match()` method returns an array of matched strings, from which the leading '#' is removed before returning the cleaned list of hashtags. This is commonly used in social media features.

Need help integrating this into your project?

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

Hire DigitalCodeLabs