JAVASCRIPT
Extracting Hashtags from a String
Learn how to effectively extract all hashtags (words prefixed with #) from any given text string using JavaScript regex, useful for social media apps.
function extractHashtags(text) {
const hashtagRegex = /(#\w+)/g;
const matches = text.match(hashtagRegex);
return matches ? matches.map(tag => tag.substring(1)) : [];
}
const text = "Check out this #awesome #javascript tutorial. It's really #helpful.";
const hashtags = extractHashtags(text);
console.log(hashtags); // ["awesome", "javascript", "helpful"]
How it works: This JavaScript function uses a regular expression `/(#\w+)/g` to find all occurrences of words prefixed with a '#' symbol. `\w+` matches one or more word characters (letters, numbers, underscore). The `g` flag ensures all matches are found. `text.match()` returns an array of matched strings, and then `map` is used to remove the '#' from each tag.