INTERNET EXPLORER? Ti consiglio di navigare questo sito con Mozilla Firefox oppure con Google Chrome.

Versione JS della funzione Trim del VB

Autore: Luca Ruggiero | Tell a Friend

Corso Java
Impara a programmare col linguaggio OOP della Sun.

Corso Javascript e DHTML
Impara a creare controlli ed animazioni!

Corso Web Design
Disegno di siti Web con HTML, CSS e Dynamic HTML.

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... io :-)

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.

IN EVIDENZA
HOT LINKS