jQuery: formattare il testo dei tweet

Una tecnica condensata in un plugin jQuery per formattare il testo dei nostri tweet.

jQuery di Gabriele Romanato

In questo articolo vorrei presentarvi una soluzione che possiamo utilizzare per trasformare un testo contenente link e hash tag in un messaggio formattato di Twitter. Vediamo insieme questa soluzione.

Creiamo il seguente plugin:


(function($) {

$.fn.tweetify = function() {
	this.each(function() {
		$(this).html(
			$(this).html()
				.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>')
				.replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>')
				.replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>')
		);
	});
	return $(this);
};

})(jQuery);

Possiamo usarlo in questo modo:


$("p").tweetify();

Per esempio, il seguente testo:


<p>@gabromanato : http://sito.com/ #css</p>

viene trasformato in questo:


<p><a href="http://twitter.com/gabromanato">@gabromanato</a> :
<a href="http://sito.com/">http://sito.com/</a>
<a href="http://search.twitter.com/search?q=%23css">#css</a></p>

Possiamo usare questo plugin quando vogliamo visualizzare i nostri tweet da Twitter.

Commenti