code

Auto-format Tweets

Used on my “About” page.

(function() {  
  var USERNAMES = /@([A-Za-z0-9_]*)\b/;
  var URLS      = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?/;
  
  function getInnerText(element) {
    element = $(element);
    return element.innerText && !window.opera ? element.innerText :
     element.innerHTML.stripScripts().unescapeHTML().replace(/[\n\r\s]+/g, ' ');
  }
  
  function linkifyTweet(li) {
    var html = li.innerHTML, text = getInnerText(li);

    text.scan(URLS, function(match) {
      html = html.sub(match[0], '<a href="#{0}">#{0}');
    });    
    html = html.gsub(USERNAMES, '<a href="http://twitter.com/#{1}/">#{0}');
    li.update(html);
  }
  
  function init() {
    $('twitter').select('li > span.tweet').each(linkifyTweet);
  }  

  document.observe('dom:loaded', init);  
})();