Retrieving hashtags from a text

If I had a string like this

var feedback =  "Yum! #yummy #delicious at #CZ"

Is there an efficient way to extract all the hashtags from the string variable?

I attempted using JavaScript's split() method, but it seems cumbersome as I have to repeatedly split each new string generated from the initial one. Are there any simpler alternatives for accomplishing this task?

Answer №1

To locate instances of a hashtag followed by any non-space characters, you can employ a simple regular expression.

"Exploring #nature and #wildlife in the #jungle".match(/#\w+/g)
// Result: ["#nature", "#wildlife", "#jungle"]

Answer №2

To find alphabetic characters in a string, use the following regex code. Feel free to customize it for other characters:

const result = myString.match(/#[a-z]+/gi);

Answer №3

Are you interested in Unicode or hashtags in languages other than English?

"Mmmm #yummy #donut at #CZ #中文 #.dou #。#?#♥️ #にほ".match(/#[\p{L}]+/ugi)
=> (5) ["#yummy", "#donut", "#CZ", "#中文", "#にほ"]

This concept is further explained in the following answer:

\p{L} matches unicode characters

u the PCRE_UTF8 modifier, this modifier turns on additional functionality of PCRE that is incompatible with Perl.

Answer №4

For those who value easy reading:

Extract hashtags from your text using: yourText.split(' ').filter(v=> v.startsWith('#'))

This code will output: ["#awesome", "#coffee", "#NYC"]

Answer №5

Here is a simple regular expression that allows emojis and numbers in hashtags without any white space:

"Mmmm #yummy #donut at #CZ#efrefg #:) #cool😎#r234#FEGERGR#fegergr".match(/#[^\s#]*/gmi);
// => ["#yummy", "#donut", "#CZ", "#efrefg", "#:)", "#cool😎", "#r234", "#FEGERGR", "#fegergr"]

One downside is that this regex may include punctuation at the end of hashtags:

"Mmmm #yummy.#donut#cool😎#r234#FEGERGR;#fegergr".match(/#[^\s#]*/gmi);
// => ["#yummy.", "#donut", "#cool😎", "#r234", "#FEGERGR;", "#fegergr"]

However, you can customize the regex to exclude certain characters, such as punctuation marks:

"Mmmm #yummy.#donut#cool😎#r234#FEGERGR;#fegergr".match(/#[^\s#\.\;]*/gmi);
// => ["#yummy", "#donut", "#cool😎", "#r234", "#FEGERGR", "#fegergr"]

Answer №6

If you're looking to include characters from any alphabet in hashtags, consider using this method:

let text = "улетные #выходные // #holiday in the countryside";
const hashtags = []
if (text.length) {
    let preHashtags = text.split('#')
    let i = 0;
    if (text[0] !== '#') i++ 

    for (null; i < preHashtags.length; i++) {
        let item = preHashtags[i]
        hashtags.push(item.split(' ')[0]) 
        // String.prototype.split() is necessary to filter out non-hashtag related strings
    }
}


console.log(hashtags) // outputs [ 'выходные', 'holiday' ]

We use if (text[0] !== '#') i++ to check if the first letter in the "text" string is not a '#'. If it's not, we skip iterating through the first element in the preHashtags Array. Otherwise, if our text string starts with a hashtag, we need to process it.

Remember to validate the resulting hashtags array. The use of null in the for loop is purely for readability purposes; you could also use

for (;i < preHashtags.length; i++)

This method ensures that all symbols, including those from non-Latin alphabets, are included, making it beginner-friendly and easy to understand. In terms of performance, it excels in Chrome (and similar browsers like node.js), but performs slightly less efficiently in Firefox and Safari, as shown in this test: .

Consider your platform - whether running code in node.js or a browser, especially if targeting MobileSafari users, when deciding on this approach.

Answer №7

Parse the content and filter out any tags that start with a hashtag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...

Choose Selectize.js to auto-populate inputs

I am currently using selectize.js for my project: $("#abc").selectize({ valueField: 'name', labelField: 'name', searchField: ['name'], plugins: ['remove_button'], createOnBlur: true, ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

How can I prevent a hyperlinked element from being clicked again after it has been clicked using JavaScript or jQuery in PHP

I am struggling with disabling the href after it has been clicked. Can someone please assist me with this? It is crucial for me to complete this PHP program. Style.css .disabled { pointer-events: none; } ...

Extracting Object Properties in JavaScript with React

Code: const [obj, setObj] = useState(() => ({ a: valueA, b: valueB, get values() { if (!this.a || !this.b) { return []; } // code... } return [this.a, this.b] }, })); Values update: useEf ...

Assistance requested with Javascript for an HTML dropdown menu

My question involves utilizing two HTML drop down menus. <select> <option value="">Please Select</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option ...

The tension settings in Chart.JS appear unusual

I recently updated to ChartJS v4.0.1 and noticed a new option called tension for curving the line chart. However, I'm not satisfied with how it looks. The tension option ranges from 0 to 1, and I've experimented with different values to enhance ...

Tips for choosing the injected HTML's List Element (li) while ensuring it remains concealed

How do I hide the list item with iconsrc="/_layouts/15/images/delitem.gif" image when this div is injected by a first party and I am a third party trying to conceal it? $("<style> what should be inserted here ???? { display: none; } </style>") ...

How to arrange three buttons in a row using CSS styling

After reviewing similar issues posted by others, I have not found a solution to my problem. Despite trying the suggested solutions, I am unable to center two buttons representing different departments on my webpage. Here is my source code: <script ...

The callback function in AngularJS filters

I'm currently using an AngularJS filter to sort through a list of items. Here is the Jade markup I am using: li(ng-repeat="parcel in parcels | filter : filterActiveAreaParcels") After the filter function runs and the elements are displayed in the DO ...

Is it possible to deactivate an anchor tag based on the result of a conditional statement that returns a string?

I've created an anchor tag (not a button) with text that redirects me to another page <StyledTableCell align="center"> <Link href={`/races/results/${race.id}`}>{race.race_name}</Link> </StyledTableCell> There is a ...

Setting up KCFinder integration in TinyMCE

I am utilizing TinyMCE as a text field, and I am in need of enabling image upload functionality within it. To achieve this, I am using KCFinder. However, I am encountering an issue where upon clicking on the 'Upload Images' button, only a white b ...

Anticipate await and fulfill promises

I'm encountering issues when attempting to refactor nested Promise.all's into async/await. It seems like there might be a misunderstanding in how I should be utilizing Promise.all and await. The goal is to iterate through an array, perform an ac ...

React blank state - State remains undefined after calling setState

I took out the imports because they are not causing any issues When I render, I set my state and it logs correctly in the console. However, when I try to map it, it comes back as null and gives me an error stating that there are no elements in the "allInf ...

What is the method for loading a subcategory based on the category by invoking a jQuery function within the <td> element of a JavaScript function that adds rows dynamically?

Whenever I click the add row button, the category dropdown list successfully loads. However, when I select an option from this category list, the subcategory does not load any list. The Javascript function responsible for adding rows dynamically is as fol ...

Invalid PDF File - Unable to Complete Download via $http

I'm facing an issue while attempting to download a PDF file using the $http service in AngularJS. Upon trying to open the downloaded file, I encounter an error message stating "Invalid Color Space" and the page appears blank. To troubleshoot this pr ...

Django will not be replacing the outdated image

My Django App is designed to display images on the browser based on user selections in the UI. Whenever there is a change in the UI, a JavaScript function is triggered that makes a call to a Django view. Each time I modify the UI in the browser, a new ima ...

Encountering Typescript errors when trying to destructure a forEach loop from the output of

There are different types categorized based on mimetypes that I am currently working with. export type MimeType = 'image' | 'application' | 'text'; export type ApplicationMimeType = '.pdf' | '.zip'; expor ...

PHP/MySQL clarification regarding time slots

Could someone assist me with this discussion I found? Due to my low reputation, I am unable to comment for further clarification. Although I grasp the solution provided in the mentioned discussion, I am struggling to comprehend how to pass the data to my ...

Tips for avoiding the persistence of an old array on the screen after refreshing and showing the new, updated array

Currently, my task involves displaying array values on a webpage. The array data is sourced from a real-time database in Firebase. After adding new values to the array or inputting another value into the database on the previous page, we are redirected to ...