Neil
Neil

Reputation: 8121

Matching a list of possible hashtags in a tweet - Javascript or jQuery

Firstly I've looked at a lot of posts on Stackoverflow but I don't see one which seems to be the definitive way. Someone always seems to find a flaw in the regex.

I already have retrieved my tweets and obviously they can contain any number of hashtags in each one.

If I have an array of possible hashtags that I want to find - ["#ENGLAND","#IRELAND","#wales"] etc.

What is a RELIABLE way to check if a tweet contains these hashtags. I don't want to call the API again, I only want to check my existing tweets, as I'm clicking on buttons to change the filtering on the fly, want to avoid rate limit if they keep clicking around for ages.

EDIT:

Example: Here is a tweet that contains #ENGLAND and #someothertag

I want to search all the tweets and just show the tweets that CONTAIN one or more of my array of tags, I already cache the tweets, I don't want to make a call containing any tags just filter the existing results!

Upvotes: 2

Views: 711

Answers (3)

menacingly
menacingly

Reputation: 738

You could store the hashtags from the entities on the element, for instance

<div class='tweet' data-hashtags='england ireland'>some_tweet</div>

And filter like this when someone clicks your button:

$('div.tweet').hide();
$('div.tweet[data-hashtags~="ireland"]').show();

It's obviously greatly simplified, but the general approach should help you avoid having to parse out the tags yourself

Upvotes: 0

danwellman
danwellman

Reputation: 9273

Why only hashify particular hashtags (which you need to specify and then maintain) when you can hashify any hashtag?

I usually use something like this:

var hashregex = /#([a-z0-9_\-]+)/gi,
    text = text.replace(hashregex, function (value) {
       return '<a target="_blank" href="http://twitter.com/#!/search?q=' + value.replace('#', '%23') + '">' + value + '</a>';
    });

Then you can just use text when you set the content to the processed tweets

Upvotes: 1

Downpour046
Downpour046

Reputation: 1671

// match a #, followed by either "question" or "idea"
var myregexp = /#(england|ireland|wales)\b/i;
var match = myregexp.exec(subject);
if (match != null) {
    result = match[1]; // will contain "england","ireland", or "wales"
} else {
    result = "";
}

If you don't know the names of the hashtags on hand replace

 var myregexp = /#(england|ireland|wales)\b/i;

with

 var myregexp = /#(\w+)/; // Use this instead

Upvotes: 0

Related Questions