Utilizzo questa funzione quando devo pulire una stringa di testo da caratteri indesiderati, come ad esempio quando carico un’immagine che è stata nominata con caratteri che potrebbero dare un indirizzo immagine non valido, oppure per una url di una pagina.
//esempio nome immagine:
let name = 'the-formation-of-chopin’s-instrumental-style';
/*
Prima utilizzo la funzione urlString che sostituisce le vocali accentate, elimina gli spazi (trim), cambia i caratteri in minuscolo e sostituisce alcuni caratteri non desiderati
poi applico il filtro regex che elimina tutti gli altri caratteri strani non desiderati
*/
function urlString(t){
t = t.trim();
t = t.toLowerCase();
t = t.replace(/\$/g,'');
t = t.replace(/ /g,'-');
t = t.replace(/à/g,'a');
t = t.replace(/á/g,'a');
t = t.replace(/è/g,'e');
t = t.replace(/é/g,'e');
t = t.replace(/ì/g,'i');
t = t.replace(/ó/g,'o');
t = t.replace(/ò/g,'o');
t = t.replace(/ù/g,'u');
t = t.replace(/ú/g,'u');
t = t.replace(/&/g,'e');
t = t.replace(/[/g,'');
t = t.replace(/]/g,'');
t = t.replace(/{/g,'');
t = t.replace(/}/g,'');
t = t.replace(/#/g,'');
t = t.replace(//g,'');
t = t.replace(/\?/g,'');
t = t.replace(/!/g,'');
t = t.replace(/^/g,'');
t = t.replace(/+/g,'');
t = t.replace(/\//g,'');
//t = t.replace(/./g,'');
t = t.replace(/,/g,'');
t = t.replace(/:/g,'');
t = t.replace(/;/g,'');
t = t.replace(/£/g,'');
t = t.replace(/%/g,'');
t = t.replace(/"/g,'');
t = t.replace(/°/g,'');
t = t.replace(/§/g,'');
t = t.replace(/ç/g,'');
t = t.replace(/@/g,'');
t = t.replace(/ñ/g,'');
t = t.replace(/\//g,'');
t = t.replace(/*/g,'');
t = t.replace(/\'/g,'-');
t = t.replace(/(/g,'');
t = t.replace(/)/g,'');
return t;
}
this.clean = function(p1){
let string = urlString(p1);
string = string.replace(/.jpg/g, '');
string = string.replace(/.jpeg/g, '');
let regex=/[^a-zA-Z-_.&\s]+/g;
string = string.replace(regex, '');
return string;
};
// in questo caso ritorna:
the-formation-of-chopins-instrumental-style