JAVASCRIPT
Extract Hashtags from Text using Regex
Discover how to efficiently extract all hashtags (words prefixed with '#') from a given text string in JavaScript using a simple and effective regular expression.
function extractHashtags(text) {
const hashtagRegex = /#(\w+)/g;
const matches = text.match(hashtagRegex);
return matches ? matches.map(match => match.slice(1)) : []; // Remove '#' prefix
}
// Usage:
console.log(extractHashtags("This is a #test with #multiple hashtags. #JavaScript"));
// Expected: ["test", "multiple", "JavaScript"]
console.log(extractHashtags("No hashtags here.")); // Expected: []
How it works: The `extractHashtags` function identifies and extracts all hashtags from a text string. It uses the regex `/#(\w+)/g` to find words starting with `#`. The `\w+` captures one or more word characters (alphanumeric and underscore). The `g` flag ensures all matches are found. The function then removes the leading '#' from each extracted tag.