jQuery: trasformare gli indirizzi e-mail testuali in link HTML

jQuery: trasformare gli indirizzi e-mail testuali in link HTML

Trasformare indirizzi e-mail testuali in link HTML è un compito reso semplice da jQuery.

Possiamo definire il seguente plugin:


(function( $ ) {
	
	$.fn.email = function() {
		return this.each(function() {
			
			var $element = $( this );
			var html = $element.html();
			var reg = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi;
			
			if( reg.test( html ) ) {
				var str = html.replace( reg, '<a href="mailto:$1">$1</a>' );
				$element.html( str );	
			}
		});
	};
	
})( jQuery );

Esempio d'uso:


$( "p" ).each(function() {
	var $p = $( this );
	var $a = $( "a[href^=mailto]", $p );
	
	if( !$a.length ) {
		$p.email();
	}
	
});

Torna su