Se combiniamo la flessibilità di jQuery con le funzioni base messe a disposizione da JavaScript possiamo ottenere risultati davvero interessanti. Ad esempio potremmo voler estrarre l'ID di un video di YouTube dai link usando la manipolazione delle sottostringhe di JavaScript. Vediamo come fare.
Abbiamo il seguente link:
<a id="youtube" href="http://www.youtube.com/watch?v=cyRqR56aCKc">YouTube</a>
L'ID del video è cyRqR56aCKc
. Il codice jQuery, organizzato in un plugin, è il seguente:
(function($) {
$.fn.youtubeID = function() {
var that = this;
var key = '';
if(!that.is('a')) {
return;
}
var href = that.attr('href');
key = href.substr(href.lastIndexOf('v=') + 2, 11);
return key;
};
})(jQuery);
Esempio d'uso:
$(function() {
var id = $('#youtube').youtubeID();
console.log(id); // cyRqR56aCKc
});
Ovviamente possiamo applicare la stessa tecnica agli URL degli elementi iframe
. In questo caso, tuttavia, dovremmo usare l'attributo src
.