ツイートの#と@とURLをリンクに変換する

Twitter API に timeline とか search を投げて返ってくるツイートはプレーンな String だったりするから、そういうのをちょちょっと整形する(#と@とURLをアンカータグでくくってリンクにする)ためのコード。

特徴としては、

  • 公式の表現に近い
    • アンカーのHTMLが以下の構造
<a><s>#</s><b>hashtag</b></a>
    • 直前、直後の文字の制限(@nameの直後が日本語でもいい、とか)
    • etc.
  • 日本語ハッシュタグ対応
  • API が返すのは http://t.co/~~ だけど、一応 google.com みたいな http(s):// なしにも対応

参考にしたURL

function tweetTrimer ( t ) {

	var text = t;
	var twitterPath = 'http://twitter.com/#!/';
	
	var patternHash = /(?:^|[^ーー゛゜々ヾヽぁ-ヶ一-龠a-zA-Z0-9a-zA-Z0-9&_\/>]+)[##]([ー゛゜々ヾヽぁ-ヶ一-龠a-zA-Z0-9a-zA-Z0-9_]*[ー゛゜々ヾヽぁ-ヶ一-龠a-zA-Z0-9a-zA-Z]+[ー゛゜々ヾヽぁ-ヶ一-龠a-zA-Z0-9a-zA-Z0-9_]*)/;
	var patternName = /(?:^|[^ーー゛゜々ヾヽぁ-ヶ一-龠a-zA-Z0-9a-zA-Z0-9&_\/>]+)@([a-zA-Z0-9_]+)/;
	var patternLink = /(http[s]?:\/\/)?([a-zA-Z0-9_]+)(\.[a-zA-Z0-9_\/\.?=]+)/g;

	var matchesLink = text.match( patternLink );
	if ( matchesLink != null ) {
		for ( var i = 0; i < matchesLink.length; i++ ) {
			text = text.replace( matchesLink[i], '<a href="' + ( ( RegExp.$1 != null ) ? '' : 'http://' ) + matchesLink[i] + '" target="_blank" class="twitter-intext-link">' + matchesLink[i] + '</a>' );
		}
	}
	
	var matchesHash;
	var matchesName;
	while ( true ) {
		var flgAllReplaced = true;
		if ( ( matchesHash = patternHash.exec( text ) ) != null ) {
			text = text.replace( patternHash, ' <a href="' + twitterPath + 'search?q=%23' + RegExp.$1 + '" target="_blank" class="twitter-intext-link"><s>#</s><b>' + RegExp.$1 + '</b></a>' ); 
			flgAllReplaced = false;
		}
		if ( ( matchesName = patternName.exec( text ) ) != null ) {
			text = text.replace( patternName, ' <a href="' + twitterPath + RegExp.$1 + '" target="_blank" class="twitter-intext-link"><s>@</s><b>' + RegExp.$1 + "</b></a>" ); 
			flgAllReplaced = false;
		}
		if ( flgAllReplaced ) break;
	}

	return text;
}

スタイルシート

a.twitter-intext-link {
	color: #0084B4;
	text-decoration: none;
}

a.twitter-intext-link:hover {
	text-decoration: underline;
}

a.twitter-intext-link s, 
a.twitter-intext-link:hover s {
	text-decoration: none;	
}

a.twitter-intext-link b {
	font-weight: lighter;
}

こんなふうにしておくと Twitter のデフォルトと同じになる。

場当たり的なことをしているので、もうちょっとスマートなやり方があるような気がぷんぷん。

「うまくいかない」「うまくいかないだろう」等ありましたらご連絡ください。