Tutorial: Clickify Your Twitter Feed in Flash

Fwitter

“Fwitter”. Deal with it.

Our Pull Twitter Updates Into Flash tutorials (Part 1 and Part 2) continue to be popular! A few folks were asking how i had taken my Twitter feed and rigged it so that people’s Twitter names and links were clickable. i promised to write tutorials on demand, so here we go.

Clickify Your Twitter Feed in Flash

Here’s the process in pseudo-code:

  1. Take the chunk of text and split it up into individual words
  2. With each word, figure out if it starts with “@” or “http:”
  3. If it does, wrap it in html tags
  4. Re-assemble the string
  5. Set the re-constituted string as your dynamic text field’s htmlText property

So, let’s start with a simple chunk of Tweet text:

“Hey everyone – @untoldent’s blog is INCREDIBLE! http://bit.ly/cXX06r”

Note: this is just a tweet i pulled at random from the Twittersphere. It could have been anything. But my blog is usually a trending topic at any given time of the day.

We’ve got two things we want to make clickable: @untoldent, which should link to untoldent’s Twitter user page, and http://bit.ly/cXX06r, which should take us to that webpage.

Splitting the String

The String class has a built-in method called split. It takes an argument that lets us carve a string up, and the resulting fragments are put into an array.

So, for example, if we have a comma-delimited string:

var fraggles:String = "Gobo,Mokey,Wimbley,Boober,Red";

we can split it using the comma as a separator. The resulting fragments are returned as an array.

var fraggles:String = "Gobo,Mokey,Wimbley,Boober,Red";
var aFraggles:Array = fraggles.split(","); // use the comma to split up the string
 
trace(aFraggles.length) // 5
trace(aFraggles[2]); // Wimbley
trace(aFraggles[4]); // Red

So in the case of our Twitter string, we want to split it up into individual words. The thing that separates one word from another is the space character. So let’s use space as an argument to split up that string:

var aWords:Array = twitterString.split(" "); // use the space character to split up the string

Note: the split method is slow, so use it sparingly. There’s not a lot going on in our Twitter reader, so we can get away with it.

Now let’s loop through each element in the aWords array – each word in the Twitter post – and determine if it’s a Twitter username (which starts with “@”), or a URL (which starts with “http:”). We’ll create an empty string to hold our final output, and run each word through a separate method.

var finalString:String = ""; // Create a new string to hold our final output
var len:int = aWords.length; // store the length of the aWords array to speed up our loop
 
// Loop through all of the words in our tweet:
for(var i:int = 0; i<len; i++)
{
    var word:String = aWords[i]; // Store an individual word in a variable
    finalString += " " + checkWord(word); // Run the word through a checkWord method, and tack the 
    // return value onto the end of our finalString (along with a space character, to space the words out)
}

Note: We’re storing the length of aWords in a variable, instead of saying i

Obviously, what’s missing is the all-important checkWord() method. Let’s build that next.

The checkWord() Method

Our checkWord() method is going to do this, in pseudo-code:

  1. Accept a word
  2. If the word starts with “@” or “http:”, wrap it in href tags and return the string
  3. Otherwise, just return exactly what was passed in

To check if a string contains a certain other string, use the String.indexOf() method. indexOf() will return the place in the string where the other string first appears.

For example, let’s find the indexOf the capital letter “W” in the string “NSFW”:

var str:String = "NSFW";
trace(str.indexOf("W")); // 3

The answer is 3, because “W” is at index 3 in the string. (Remember that strings and arrays are 0-based – the first element is at index 0, the second element is at index 1, and so on.)

If the thing you’re looking for can’t be found anywhere in the string, the indexOf() method will return an index of -1:

var str:String = "NSFW";
trace(str.indexOf("pictures of adorable kittens")); // -1

Substring

The last thing you need to know how to do is to grab just a piece of a string. This is because the twitter name comes through with an @ symbol at the front, for example @untoldent. But we need to link to http://www.twitter.com/untoldent. Notice there’s no “@” in that URL.

We need to extract just the username from the string, without the “@”. We can use the String.substr (substring) method to do that.

The way String.substr() works is that you pass it a start point and an end point, and it rips that section out of the string and returns it.

So, check it out:

var str:String = "manboobs";
trace(str.substr(3,7))); // boobs

The letter at index 3 of “manboobs” is “b”. (Remember – we start counting at zero.) We rip the section out up to index 7, which is that last letter, “s”. So what’s returned are the letters from index 3 to index 7 – “boobs”.

If you want to rip out a chunk of your string from a certain index point to the last letter in the string, you can use the String.length property.

var str:String = "manboobs";
trace(str.substr(3,str.length))); // boobs

If you’re on high alert and paying really close attention, you’ll notice that str.length takes us one index point past the end of our string. (“manboobs” is 8 characters long, and there IS no letter at index 8.) Flash just ignores us if we try to grab more of the string than actually exists. So technically, this is also valid:

var str:String = "manboobs";
trace(str.substr(3,5000))); // boobs

Armed with this knowledge, we can build our checkWord() method.

Let’s Do This Thing

private function checkWord(word:String):String
{
 
   if(word.indexOf("http:") == 0)
   {
         // This word starts with "http:" at index 0 (the beginning of the word)
 
         // Wrap it in html href (anchor) tags:
         return "<a href='" + word + "'>" + word + "</a>";
   } else if (word.indexOf("@") == 0) {
         // This word starts with "@" at index 0 (the beginning of the word)
 
         var justTheName:String = word.substr(1, word.length); // Remove the "@" from the username
         // We do this because we need to link to http://www.twitter.com/untoldent (for example),
         // not http://www.twitter.com/@untoldent
 
         // Wrap it in html href (anchor) tags:
         return "<a href='http://www.twitter.com/" + justTheName + "'>" + word + "</a>";
   } else {
        // There's nothing special about this word.  Return it as-is.
        return word;
   }
}

Note: Did you notice the use of single quotation marks and double quotation marks? You need to wrap you url in quotes, but since we’re already using double-quotation marks around our string, we need to use single-quotation marks to wrap the url, or they’ll interrupt our string definition and screw things up.

The Money Shot

So far, we’ve turned this:

"Hey everyone - @untoldent's blog is INCREDIBLE!  http://bit.ly/cXX06r"

into this:

"Hey everyone - <a href='http://www.twitter.com/untoldent'>@untoldent's</a> blog is INCREDIBLE!  <a href=''>http://bit.ly/cXX06r</a>"

The very last step is to use the htmlText property of your dynamic text box and stuff it with that fancy new string. Assuming you have a dynamic text box called twitterTxt, do this:

twitterTxt.htmlText = finalString;

You’ll now have clickable links inside your text field.

Extra Credit

If you’re super-astute, you’ve noticed that this code won’t actually work! That’s because the Twitter string says “@untoldent’s”, not “@untoldent”. The apostrophe-s is going to screw your code up, because you’ll be linking to http://www.twitter.com/untoldent’s, which is not a valid URL.

Using what you’ve learned in this tutorial, can you augment your checkWord() method to detect a “‘s” at the end of a Twitter user name and rip it out?

Further Reading

i hope this tutorial was informative and helpful! For more Actionscript and Flash tutorials, thrill to our Flash and Actionscript 911 book.

33 thoughts on “Tutorial: Clickify Your Twitter Feed in Flash

  1. Mitch Rawrockin

    Thank you very much, I have to try to get it working later, tried just ago but its pretty hard for a dummy like me :D..my brain hurts.. thanks again and nice tutorial

    Mitch

    Reply
  2. Jimmy McRegular

    First off, while I use them I hate regular expressions. I find them hard to read, hard to maintain, and prone to subtle errors. That being said, this sounds like a job for regular expressions – especially if you need to support more than links (mailto perhaps?). Regular expressions would turn your routine into 1 line obscure code (no loops!) that would make Unix command liners salivate.

    Something like this:
    twitterTxt.htmlText = twitterTxt.htmlText.replace(
    new RegExp(“((?:http|ftp)://)([a-z0-9_-]+\.[a-z0-9_-]+)(\.[a-z0-9_-]*)”, “ig”)
    , “$1$2$3
    );
    – not sure if this works, just a guess

    Regular expressions use a separate programming language that focuses on string parsing. The language is so powerful that 1 letter can yield great healing and great destruction. It will change they way you think, then leave you trapped in its byzantine labyrinth.

    The regular expression fwitter version would make a great followup article.
    More importantly, afterward you can look down on everyone that doesn’t use them,
    which is the true reason why they exist.

    Example stolen from:
    http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000112.html
    – they have a more readable version

    twitterTxt.htmlText

    Reply
    1. Ryan

      Jimmy – yeah, i DESPISE regexes. And try to explain them in a beginner tutorial like this one.

      Since i don’t fully grasp how to write them (and not for lack of trying), i always steal them. And whenever i do THAT, there’s always some yahoo in the comments thread saying “yeah, but this regex won’t work if someone accidentally types a COMMA in the left-third of the email field!” or whatever, and then my confidence in other people’s work is shaken.

      Regexes have their place, but that place ain’t here – i can’t teach them, and beginners can’t learn them. (Or i’m just an especially stupid beginner.)

      Reply
  3. Jimmy McRegular

    Beginners can’t learn them? Incorrect. No-one, including professionals, can learn them.
    Regular Expressions aren’t meant to be understood, that’s what makes them so great!
    i.e. You launched a rocket into space? Not bad. I capitalized the first word in every sentence.

    You might be the first person to actually explain Regular Expressions to the masses.
    You have the chance to become a hero… A HERO!!!

    Reply
  4. Mitch Rawrockin

    Hey Ryan, thanks for all your devoted work, mine is working mostly, thoughI havent been able to get these links to work but will try some more, ( http://mitchelbagijn.com/twitterapp/fountain.html )

    I’m just wondering if I’m able to get the XML-data imported from a hashtag instead of a user..
    I tried to get it to work by changing my php file to:

    (I set the twitterId to ‘nowplaying’ resulting in: http://search.twitter.com/search.atom?q=%23nowplaying.xml)
    however I’m getting the tweets from a certain user named nowplaying instead of the #nowplaying ..
    any thoughts?

    thanks

    mitch

    Ive also tried these:

    http://search.twitter.com/search?q=%23nowplaying
    http://search.twitter.com/search.atom?lang=en&q=%23nowplaying
    http://search.twitter.com/search.atom?q=%23nowplaying

    Reply
    1. Ryan

      Mitch – try cracking open the php script and modifying what it calls. That’s where the magic happens. myTwitterID is just passed along blindly.

      – Ryan

      Reply
  5. Mitch Rawrockin

    I typed the php code after this line

    “I tried to get it to work by changing my php file to:”

    Reply
  6. Mitch Rawrockin

    so you are saying that it is possible to get tweets from a hashtag just by changing the address? if so I will try to get it working some more.. thanks

    Reply
    1. Ryan

      Mitch – that is my hypothesis, yes. The php file should just be calling a URL. Tinker with that URL by changing it the search format you described.

      Reply
  7. Rob Segal

    Now I don’t know this Jimmy McRegular character but I am inclined to agree with him and I feel the need to add my input into the discussion. Regular expressions have helped me immensely at my job over the past couple of months. Something which has helped greatly while using them is to be able to see with each added token to my expression what it will select in the target string. This has been possible with a tool called RegEx Coach (http://weitz.de/regex-coach/) and the regular-expressions.info website (http://www.regular-expressions.info/). I highly recommend them as some sane ways to learn and play around with regular expressions.

    Reply
    1. Ryan

      Rob – that’s the kind of tool i’ve been looking for. But download? For serious? UGH.

      i’m really wondering why there isn’t a simple Flash or AIR tool somewhere that does the same thing. (Or IS there??)

      – Ryan

      Reply
  8. Mitch Rawrockin

    Hey Ryan!

    thanks for all your tutorials on twitter, it really helped me out A LOT!!

    when I started this project I didn’t knew anything about AS3 and not much more about AS2..

    I managed to build a dynamic twitterapp :)

    and for the @untoldent’s [‘s] I used this:

    var wordZonderHaakje:String = word;
    wordZonderHaakje = wordZonderHaakje.split(“‘s”).join(“”);
    var justTheName:String=wordZonderHaakje.substr(1,word.length);

    thanks again!

    Reply
  9. Ties

    Ryan, first of all: thanks!
    I kind of understand all the code now, but I can’t figure out how to implement it in the Main.as from your previous tutorial. I tried, but all these errors showed up like “The private attribute may be used only on class property definitions.” I understand that it’s because of my noobieness, but can you give me a hint here?

    Reply
  10. Ties

    Thanks, it sure did help, only two errors left!
    I get “1137: Incorrect number of arguments. Expected no more than 0.

    Reply
  11. Leslie

    Hi Ryan — I downloaded your code a couple of weeks ago and love it — your explanations are great! The problem I have been running into is that no matter how I format the html text that I assign to the twitter_txt field, it is overridden by a different textformat. I can’t tell where it is coming from — seems like it is something simple. Do you know what is going on?

    Reply
    1. Ryan

      Leslie – what’s the difference between the two? What does the unwanted formatting look like? And is your dynamic text box created and placed on the stage “by hand”, or did you create it dynamically with code?

      Reply
  12. Leslie

    OK, what I just posted was not helpful because it just displayed everything as html. The text box I am using was not created with code but was placed on the stage — it’s straight from your code. When I hand code the way I want the html formatted within a string, that code shows when I do a trace(twitter_txt) but it is surrounded by other textformatting that takes precedence over what I have coded. I see your point, if I hand code the text field, I can do everything from scratch. I’m just confused as to why the twitter_txt field that is part of your code is a textformat field when I don’t see it being declared as such anywhere. By the way, I really appreciate the fact that you responded so quickly!

    Reply
    1. Ryan

      Leslie – this is a super-simple thing, but did you try clicking the “HTML” button (looks like “”) on your text field?

      Reply
  13. Leslie

    You’re right, Ryan — it was a super simple thing. Thank you — it works! Excellent site and I appreciate your help!

    Reply
  14. Dimitris Gkikas

    Hi Ryan!!
    Great tutorial and very helpful comments for you.This is great. i downloaded yesterday for a project that i want to do.So In order to make the text looks cleaner and better i used some regular expressions to get rid of
    #, @ , or http links from twitter (By the way the http links is this regular expression :”http:\/\/[\\w\\.\\/]+”) but i still haven’t figured out how can i put comments (“…”) in the start and in the end of every sentence. (for example instead of this… hello lyla should appear this… “hello lyla” ).
    I would be great full if u can recommend me an idea.
    Thank you

    Reply
    1. Ryan

      Dmitris – if you’re using regular expressions, you’re already miles ahead of me! i’ve never had any luck with them.

      i can’t quite figure out what you’re trying to do. Are you trying to put quotation marks – ” ” – around everything, or are you trying to put an ellipsis (the dot dot dot …) around everything?

      If i wanted to wrap an entire string in something, i’d just do this:

      myOriginalString = “This is something someone said on Twitter.”;

      myNewString = “…” + myOriginalString + “…”;

      If you want double-quotation marks, you can wrap them in single quotation marks:

      myNewString = ‘”‘ + myOriginalString + ‘”‘;

      i’ll add some space to that so you can see what’s going on: ‘ ” ‘

      Is that what you’re trying to do?

      – Ryan

      Reply
  15. Lynnie

    So the 1st two tutorials worked absolutely great for me until I got to this one!!
    Where do I place the code??

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *