Skip to content

Instantly share code, notes, and snippets.

@storkontheroof
Last active July 29, 2016 05:12
Show Gist options
  • Save storkontheroof/8775cc6591f758f9c9fd220c35f9be13 to your computer and use it in GitHub Desktop.
Save storkontheroof/8775cc6591f758f9c9fd220c35f9be13 to your computer and use it in GitHub Desktop.
A simple javascript parser for properly displaying a Tweet (e.g. with links) from a Twitter feed
// The parser expects a single node from a twitter feed and returns HTML
// Usage:
// var tweets = <some array with tweets from an API call>;
// Parse first tweet:
// var tweetHTML = TwitterParser.parseText(tweets[0]);
// console.log(tweetHTML);
(function (window, undefined) {
function escapeHTML(html) {
var text = document.createTextNode(html);
var div = document.createElement('div');
div.appendChild(text);
return div.innerHTML;
}
function parseText(tweet) {
if (!(tweet.entities)) {
return escapeHTML(tweet.text)
}
var pieces = tweet.text.split(' ');
var piecesParsed = [];
for (var i = 0; i < pieces.length; i++) {
var piece = pieces[i];
if (piece.indexOf('@') === 0) {
var mention = tweet.entities.user_mentions.shift();
piece = "<a title='" + escapeHTML(mention.name) + "' href='http://twitter.com/" + escapeHTML(mention.screen_name) + "' target='_blank'>" + escapeHTML(piece) + "</a>";
}
else if (piece.indexOf('#') === 0) {
var hashtag = tweet.entities.hashtags.shift();
piece = "<a href='http://twitter.com/search?q=" + escape("#" + hashtag.text) + "' target='_blank'>" + escapeHTML(piece) + "</a>";
}
else if (piece.indexOf('http') === 0) {
var url = tweet.entities.urls.shift();
piece = "<a href='" + escapeHTML(url.url) + "' target='_blank'>" + escapeHTML(piece) + "</a>";
}
piecesParsed.push(piece);
};
return piecesParsed.join(' ');
};
window.TwitterParser = {
parseText: parseText
};
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment