JAVASCRIPT
Extract All Hashtags from Text using Regex
Discover how to efficiently extract all hashtags from any given text string using a JavaScript regular expression and the `matchAll()` method.
function extractHashtags(text) {
const hashtagRegex = /#(\w+)/g; // 'g' for global match
const matches = [...text.matchAll(hashtagRegex)];
return matches.map(match => match[1]); // match[0] is full match, match[1] is captured group
}
// Examples:
const postText = "This is a #great #day for #learning about #JavaScript and #Regex.";
console.log(extractHashtags(postText)); // ["great", "day", "learning", "JavaScript", "Regex"]
const noHashtags = "Just a plain text sentence.";
console.log(extractHashtags(noHashtags)); // []
How it works: The regex `/#(\w+)/g` is used to find all occurrences of hashtags. `#` matches the literal hash symbol, `(\w+)` captures one or more word characters (letters, numbers, underscore) into a group, and the `g` flag ensures all matches are found, not just the first. `String.prototype.matchAll()` returns an iterator for all matches, which is then converted to an array and mapped to extract just the captured hashtag words (the content after the `#`).