![]() |
|
Homepage |
Javascript |
Versione JS della funzione Trim del VB | |
Versione JS della funzione Trim del VB
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 :-)
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
Una slidegallery con jQuery
Pagamenti online con PayPal e PHP
Breve guida a jQuery
Effetto ombra su testo con Photoshop
Guadagna col tuo sito grazie a TradeD...
Guida XHTML
Riscrivere le URL con Asp
Riavviare IIS
HTTP 500 internal server error
Generare password casuali in Javascri...
Errore 80004005: Cannot update. Datab...
Introduzione ad Ajax ed Asp con Jscri...
Referenze dei Tag Html
Stringhe di connessione via ODBC e Ol...
Referenze dei fogli di stile Css
Le espressioni regolari in Javascript
|
||||
© 2001/2010 lukeonweb.net - A cura di Luca Ruggiero, Partita IVA 05564851219 -
Privacy |
Pubblicità |
Contatti
| |||||