with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Twita@talinkahashify your tweets

Monday, May 25th, 2009

Well hello everyone. I had previously tweeted about this a few weeks ago… but sometimes I forget more folks follow this blog than my Twitter.

If any of you use our Twitter API to embed your latest statuses on your website, here is a simple little script that will do a few niceties for you. This includes linkafying, hashtagifying, and of course the most important, atify (aka: “at replies”). check out the source, and use it as such:

tweet code

ify.clean('your tweet text');

Thus making transforming a tweet such as the following:

Before and After

Bfore
Hey @ded. You should #stfu! and use http://canon.com #rant.
kthxbye @erin http://www.google.com/search?q=canon+rules

After
Hey @<a href="http://twitter.com/ded">ded</a>.
You should #<a href="http://search.twitter.com/search?q=%23stfu">stfu</a>!
and use <a href="http://canon.com">http://canon.com</a>
#<a href="http://search.twitter.com/search?q=%23rant">rant</a>.
kthxbye @<a href="http://twitter.com/erin">erin</a>
<a href="http://www.google.com/search?q=canon rules">
http://www.google.com/se...</a>

Download: source | minified

23 Responses to “Twita@talinkahashify your tweets”

  1. Andrea Giammarchi

    I can’t believe I created basically the same script one hour ago to keep working over a web client via Full PHP Proxy … anyway, guys any chance the API will work as is for XML when there are no result? Nothing happen with json protocol, but maybe you already know it. Good stuff.

  2. Andrea Giammarchi

    P.S. for the link I simply returned this:
    return m1.concat(’‘, link.substr(0, 24), link.length > 25 ? ‘…’ : ”, ‘‘);
    don’t see the reason to make it longer, while I guess you forgot quotes ;-)

  3. Dustin Diaz

    @Andrea,
    What a bummer :( Sorry to hear. As for JSON protocol, I guess they assume you’re using it for complete frontend purposes, and that we’d be doing our own error handling (that’s just my guess, the API was created before I joined Twitter).

    Other than that, I’m still sorting out a small bug in the linkafyer regex. it was simplified to fit the largest use cases (eg: the “\S”)… but that’ll be working better soon enough.

  4. Andrea Giammarchi

    ehr … I guess tml is fully enabled, sorry for that, I meant:

    return m1.concat(”, link.substr(0, 24), link.length > 25 ? ‘…’ : ”, ”);

  5. Dustin Diaz

    @Andrea,
    Use the postable link when adding HTML to the comments :)

  6. Dustin Diaz

    Ah, I see, that’s a bit more clever, should have thought of that! thanks.

  7. Andrea Giammarchi

    cheers Dustim, I just simply would like to post the snippet but I think I’ll twit :D
    about json you wrote in the API to use the extension but for some piece of API it does not generate anything rather than an object with {hash:{error:”Not Foud”}} it’s just a quick one, the rest is fine.

  8. Andrea Giammarchi

    and finally, I never wrote Dustim … (I better go now, I am keep doing mistakes today! On twitter @WebReflection, cu)

  9. Andrea Giammarchi

    last try, just as suggestion:

    var ify = function() {
    return {
    "link": function(t) {
    return t.replace(/(^|\s+)(https*\:\/\/\S+)/g, function(m, m1, link) {
    return m1.concat('<a href="', link, '">', link.substr(0, 24), 25 < link.length ? '...' : '', '</a>');
    });
    },
    "at": function(t) {
    return t.replace(/(^|\s+)\@([a-zA-Z0-9_]{1,15})/g, ‘$1@<a href=”http://twitter.com/$2″>$2</a>’);
    },
    “hash”: function(t) {
    return t.replace(/(^|\s+)\#([a-zA-Z0-9_]+)/g, ‘$1#<a href=”http://search.twitter.com/search?q=%23$2″>$2</a>’);
    },
    clean: function(tweet) {
    return this.hash(this.at(this.link(tweet)));
    }
    };
    }();

  10. Dustin Diaz

    actually, i fixed a few things up, i think it’s best now.

  11. Andrea Giammarchi

    @Dustin, definitively better, but you forgot quotes in the link ( a href= + and not a href=” + ” ) and as I wrote in my example, you do not need a runtime function plus string concatenation for both @ and #, let’s browsers do the dirty job internally and use just the string with $1 for the “startwith=emptystring” or the space and $2 for the name. Good to know the name has 15 chars limit. P.S. specially in Explorer, svar.concat($1, $2, $3, $4, $5); is much faster than svar + $1 + $2 + $3 + $4 + $5 (usually faster when + is present more than twice)
    Best Regards

  12. Dmitry Baranovskiy

    As many others I wrote the same function recently. Check it out. BTW your regexps allow some XSS. You should not allow quotes in URLs.
    ify: function (tweet) {
    var res = tweet.replace(/(^|\s)(?:#([\d\w_]*)|@([\d\w_]{1,15}))|(https?:\/\/[^\s"]+[\d\w_\-])|([^\s:@"]+@[^\s:@"]*)/gi, function (all, space, hash, at, url, email) {
    var res = ‘<a href=”mailto:’ + email + ‘”>’ + email + ‘</a>’;
    hash && (res = space + ‘#<a href=”http://search.twitter.com/search?q=%23′ + hash + ‘”>’ + hash + ‘</a>’);
    at && (res = space + ‘@<a href=”http://twitter.com/’ + at + ‘”>’ + at + ‘</a>’);
    url && (res = ‘<a href=”‘ + encodeURI(decodeURI(url.replace(/<[^>]*>/g, “”))) + ‘”>’ + url + ‘</a>’);
    return res;
    });
    return res;
    }

  13. Andrea Giammarchi

    @Dmitry, this script would like to replace what twitter returns and if there are XSS problems, they arrive directly from the source. In few words, you retrieve messages from twitter and you show them. It is not not our problem to take care about XSS in both ways (show or send) don’t you agree?

  14. Andrea Giammarchi

    Hi Dustin, a quick Off Topic about postable. Here you have the new link, hope you’ll appreciate it ;-)
    P.S. obviously the link has been encoded with the service itself.
    Regards

  15. Andrea Giammarchi

    … ok, my blog accepted that link … let me try again via code
    javascript:(function(src,w,h,i,s){if(this.WebReflectionEncode)return this.WebReflectionEncode();function p(){s.top=document.documentElement.scrollTop+'px'};try{i=document.createElement('<iframe src="'+src+'"></iframe>')}catch(e){i=document.createElement('iframe');i.src=src};s=i.style;s.border='1px solid black';s.width=w+'px';s.height=h+'px';s.position='absolute';s.right=0;s.zIndex=99999;p();w=setInterval(p,250);(document.body||document.documentElement).appendChild(i);this.WebReflectionEncode=function(){clearInterval(w);i.parentNode.removeChild(i);w=h=s=i=null;this.WebReflectionEncode=null;}})('http://www.3site.eu/encode/',280,320);
    otherwise in my blog. Regards

  16. Dmitry Baranovskiy

    @Andrea, No I do not agree. I could post a tweet that, if it was imported into page by Dustin’s script could give me ability to run JavaScript from the page. We all know what that mean.
    Of course if you showing just yours tweets, you are pretty safe.

  17. Andrea Giammarchi

    @Dmitry … you read tweets from twitter, you post tweets in twitter … if you display realtime while posting via Ajax in background you are damaging only yourself while once you receive tweets from twitter the problem would not exist, script stuff will be encoded. Am I wrong? Anyway, as programmer, paranoia is always a must, so I agree :D

  18. Nick Dunn

    Great work! I’ve ported this over to XSLT for use with Symphony CMS, in case anyone is interested.

    http://symphony-cms.com/downloads/xslt/file/22122/

    No regular expression support, so I needed to resort to some nasty assumptive string munching :-(

  19. Dustin Diaz

    @Nick, Very cool :)

  20. Ray Nimmo

    welcome back Dustin, just a wee off topic question.

    You mention the existing Twitter API, which was obviously written before your time. But coming in to twitter as a new employee, what are your initial thoughts on the back end code and can you see room for improvement.

  21. Remy Sharp

    Hey Dustin, just spotted your latest post. I’ve been using something similar for the Twitter JS script I wrote a while back ( http://code.google.com/p/twitterjs/ ) but I’d say the regex for the link is slightly tighter in my code and handles edge cases better (erhem…I /believe/!).

    Basically there’s a couple of cases where the regex fails, in particular if there’s any erroneous characters trailing or proceeding the link (such as brackets) - both for links but also for at linkage.

    I’ve mocked up a quick test with a tweaked version of ify based on my twitterjs linkify function based on real tweets that I’ve marked as favourites over time:

    http://jsbin.com/ijopi (edit with: http://jsbin.com/ijopi/edit )

    Hope that’s of help :-)

  22. Lucien Relation

    I am using Twitterfox and I am quite happy about it. I can do my job on the computer and still tweet easily.

  23. Diyet Zay?flama

    Hi Dustin. I have read a lot of articles here and sholud say a bit cofused. I need to learn more. All these codes a bit complex for me. But thank you very much and regards.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

All content copyright © 2003 - 2009 under the Creative Commons License.

Archives | Blog Search