JAVASCRIPT
Extract Hashtags from Text
Efficiently extract all hashtags (e.g., #topic) from user-generated text using a JavaScript regex, ideal for social media features or content categorization.
function extractHashtags(text) {
const hashtagRegex = /#(\w+)/g;
const matches = text.match(hashtagRegex);
return matches ? matches.map(match => match.substring(1)) : [];
}
// Example usage:
const tweet = "This is a #great day for #coding! #javascript #regex";
console.log(extractHashtags(tweet)); // ["great", "coding", "javascript", "regex"]
const noHashtags = "No hashtags here.";
console.log(extractHashtags(noHashtags)); // []
How it works: This JavaScript function extracts all hashtags from a given text string. It uses a regular expression `/#(\w+)/g` to find patterns that start with `#` followed by one or more word characters (letters, numbers, or underscore). The `g` flag ensures all occurrences are found. The function then processes the matches to return just the hashtag text without the `#` symbol.