JAVASCRIPT
Extract Hashtags from a String
Learn to efficiently extract all hashtags (words prefixed with '#') from a given text string using a JavaScript regular expression.
function extractHashtags(text) {
const hashtagRegex = /(#\w+)/g;
const matches = text.match(hashtagRegex);
return matches || []; // Return an array of hashtags or an empty array
}
// Usage:
// const post = "This is a #great day for #coding and #learning!";
// console.log(extractHashtags(post)); // ["#great", "#coding", "#learning"]
// const noHashtags = "Just plain text.";
// 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` which looks for a '#' character followed by one or more word characters (alphanumeric and underscore), with the `g` flag to find all occurrences. The `match()` method returns an array of all matching hashtags or `null` if none are found.