Skip to content

Instantly share code, notes, and snippets.

@dexit
Created October 22, 2019 10:26
Show Gist options
  • Save dexit/18c5ec0842ecda487fe9c484ca62f178 to your computer and use it in GitHub Desktop.
Save dexit/18c5ec0842ecda487fe9c484ca62f178 to your computer and use it in GitHub Desktop.
Automatically add ALT from Image file name
jQuery( document ).ready(function() {
String.prototype.filename=function(extension){
var s= this.replace(/\\/g, '/');
s= s.substring(s.lastIndexOf('/')+ 1);
return extension? s.replace(/[?#].+$/, ''): s.split('.')[0];
}
jQuery("img").each(function () {
var alt = jQuery(this).attr('alt');
if(alt === ""){
var namefile = jQuery(this).attr('src').filename();
var rep = namefile.replace(/[_#?%*$@!=&]/g,'-');
var temp = rep.split('-');
var alt ='';
for (i = 0; i < temp.length; i++) {
alt = alt+' '+temp[i];
}
jQuery(this).attr('alt',alt);
}
if(alt === undefined){
var namefile = jQuery(this).attr('src').filename();
var rep = namefile.replace(/[_#?%*$@!=]/g,'-');
var temp = rep.split('-');
var alt ='';
for (i = 0; i < temp.length; i++) {
alt = alt+' '+temp[i];
}
jQuery(this).attr('alt',alt);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment