I’m using the Twitter API to get top 5 tweets for my app. I need to highlight, or link parts of the tweets differently. Ex, #
‘s will be orange, @
‘s will be red and clickable, etc…
From their API, they offer user_timeline
endpoint:
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
But the tweets
object’s text returns with those special characters embedded within it. I don’t see options to pull out those @, # and href
from the object:
Tweets object:
{
...
text: "This is some text @tagName that I'd like to #parse here https://t.co/m9Addr4IlS",
...
}
While I can write my own string parser to look for those things, is there something the Twitter API offers to handle this?
EDIT: <tweets>
is an Angular directive that ng-repeats
over my tweets from ModulesService
. replace
doesn’t seem to be appending the DOM tags
scope.getTweets = function() {
ModulesService.getTweets().success(function(res) {
if (res && Array.isArray(res)) {
scope.tweets = parseTweets(res);
}
});
};
scope.getTweets();
var parseTweets = function (tweets) {
tweets.forEach(function (tweet) {
tweet.text.replace(/(@[^ ]+)/g, '<a class="user">$1</a>').
replace(/(#[^ ]+)/g, '<span class="hash">$1</span>').
replace(/(https?://[^ ]+)/g, '<a href="$1">$1</a>');
console.log('tweet!', tweet.text); //does not contain altered HTML
});
return tweets;
};
HTML:
<div ng-repeat="tweet in tweets" class="post-body clearfix">
{{tweet.text}}
</div>
3
Answers
Try:
recommended solution
The library twitter-text does the work for you.
As per their examples:
autolink
extract entities
Using that solution will save you from re-inventing the wheel and will provide you with a stable working code 🙂
alternative
Inside the tweet object that you receive from the
user_timeline
API endpoint, theentities
property stores the list ofurls
,hashtags
andmentions
included inside the tweet. These contain the text content as well as the position (start / end character indices) of each entity.Example hashtag entity:
cf Entities documentation for more info.
Loop over the returned tweets and modify the tweet text according to some conditions: