
La funzione Trim() è un gioiellino proprietario del VBScript che serve ad eliminare spazi vuoti all'inizio ed alla fine di una stringa. Purtroppo il Javascript non ne è nativamente dotato, ma per il principio che nulla si crea e nulla si distrugge, tutto si trasforma (forse non c'entra nulla, ma fa figo dirlo!) la funzione Trim() ce la creiamo noi...
Di seguito il codice abbondantemente commentato, pronto per l'utilizzo immediato:
function Trim(StrToTrim)
{
// CONTROLLA CHE IL VALORE IN INPUT SIA DI TIPO STRING
if (typeof StrToTrim != "string")
{
return StrToTrim;
}
// CATTURA IL PRIMO CARATTERE DELLA STRINGA
// PER CONTROLLARE CHE NON SIA UNO SPAZIO VUOTO
var StrBlank = StrToTrim.substring(0, 1);
// ELIMINA LO SPAZIO VUOTO DALLA PRIMA POSIZIONE DELLA STRINGA
while (StrBlank == " ")
{
StrToTrim = StrToTrim.substring(1, StrToTrim.length);
StrBlank = StrToTrim.substring(0, 1);
}
// CATTURA L'ULTIMO CARATTERE DELLA STRINGA
// PER CONTROLLARE CHE NON SIA UNO SPAZIO VUOTO
StrBlank = StrToTrim.substring(StrToTrim.length - 1, StrToTrim.length);
// ELIMINA LO SPAZIO VUOTO DALL'ULTIMA POSIZIONE DELLA STRINGA
while (StrBlank == " ")
{
StrToTrim = StrToTrim.substring(0, StrToTrim.length-1);
StrBlank = StrToTrim.substring(StrToTrim.length-1, StrToTrim.length);
}
// ELIMINA POTENZIALI SPAZI VUOTI MULTIPLI
// ALL'INIZIO ED ALLA FINE DI UNA STRINGA
while (StrToTrim.indexOf("") != -1)
{
StrToTrim = StrToTrim.substring(0, StrToTrim.indexOf(""));
StrToTrim += StrToTrim.substring(StrToTrim.indexOf("") + 1, StrToTrim.length);
}
// RESTITUISCE IL VALORE FINALE SENZA SPAZI VUOTI DI CONTORNO
return StrToTrim;
}
Di seguito ecco come si può richiamare la nostra funzione Trim() da un'altra applicazione Javascript:
document.write(Trim(" lukeonweb "));
Il risultato sarà la stringa lukeonweb priva degli spazi vuoti iniziali e finali.
(Cherek - Venerdì, 23 aprile ore 23,04 )