Caspert
Caspert

Reputation: 4363

How to generate the markup of an tweet?

I was wondering how I can set plain text and links inside a span or whatever. Below my working code:

$(document).ready(function() {

// Get latest tweet
// twitter id
var user = 'USERNAME';

// count
$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + user + '&count=1&include_rts=1&callback=?', function(data)      {

    // result
    var tweet = "";
        for (i = 0; i < data.length; i++) {
            tweet += data[i].text + "</br></br>";
        }

    // links
    tweet = tweet.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(url) {
        return '<a target="_blank" href="'+url+'">'+url+'</a>';
    }).replace(/B@([_a-z0-9]+)/ig, function(reply) {
        return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });

    // output
    $("#tweet").html(tweet);
});

});

Thanks in advance.

Upvotes: 0

Views: 129

Answers (1)

karthikr
karthikr

Reputation: 99620

You can do this:

var span = $(document.createElement('span')).html(tweet);
$("#tweet").html(span);

Checkout this fiddle

Upvotes: 1

Related Questions