JAVASCRIPT
Extract Hashtags from Text with Regex
Learn how to use a regular expression in JavaScript to efficiently extract all hashtags (e.g., #webdev, #javascript) from a given string.
function extractHashtags(text) {
const hashtagRegex = new RegExp(/#(\\w+)/g);
const matches = text.match(hashtagRegex);
if (matches) {
return matches.map(match => match.substring(1)); // Remove '#' prefix
}
return [];
}
// Usage examples:
// const tweet = "I love #coding and #javascript. It's a #fun day!";
// console.log(extractHashtags(tweet)); // ["coding", "javascript", "fun"]
// console.log(extractHashtags("No hashtags here.")); // []
How it works: This JavaScript function `extractHashtags` uses a regular expression to find and extract all hashtags from a given text string. The pattern `/#(\\w+)/g` looks for a '#' character followed by one or more word characters (`\w`, which includes letters, numbers, and underscore). The `g` flag ensures all occurrences are found. It then maps the matches to remove the leading '#' from each extracted hashtag. Backslashes within the regex literal (e.g., `\w`) are correctly escaped as `\\w` for JSON string representation.