JavaScript Base Library
Vi è mai capitato, sviluppando codice client-side, di porvi domande come: "ma come si calcolano le dimensioni di un elemento?" oppure: "devo validare un indirizzo email ma quella regular expression proprio non me la ricordo!" o ancora: "accidenti, sarebbe meglio eliminare gli spazi iniziale da questa stringa". Beh, a me sì! E molto spesso. Così ogni volta mi trovo a scartabellare tra i vecchi progetti alla ricerca di "quella funzione che mi ricordo di avere già scritto" oppure ad effettuare una ricerca in Internet di quel codice che mi sembra faccia al caso mio. Stanco di queste peregrinazioni, ho messo tutte le funzioni indispensabili in bel file JavaScript: spero possa essere utile anche a voi come lo è a me!
String: trim, lTrim e rTrim
In JavaScript si sente la mancanza delle funzioni Trim(), LTrim() e RTrim() di VBScript per rimuovere gli spazi iniziali e/o finali da una stringa:
function trim()
{
var newstr = this + "";
newstr = newstr.lTrim();
newstr = newstr.rTrim();
return newstr;
}
String.prototype.trim = trim;
function lTrim()
{
var newstr = this + "";
while(newstr.charAt(0) == " ")
newstr = newstr.substring(1, newstr.length);
return newstr;
}
String.prototype.lTrim = lTrim;
function rTrim()
{
var newstr = this + "";
while(newstr.charAt(newstr.length - 1) == " ")
newstr = newstr.substring(0, newstr.length - 1);
return newstr;
}
String.prototype.rTrim = rTrim;
String: replaceText
Il metodo replace è molto potente, accettando una regular expression per la definizione del criterio di sostituzione. Spesso però sarebbe sufficiente un semplice metodo di sostituzione di caratteri:
function replaceText(pattern, substitute)
{
return this.split(pattern).join(substitute);
}
String.prototype.replaceText = replaceText;
Verifica di una data
Per verificare se i valori di giorno, mese e anno corrispondono ad una data valida:
function isDate(year, month, day)
{
var d = day + "";
var m = month + "";
var y = year + "";
if((d == "") || ( m == "") || ( y == ""))
return false;
if(isNaN(d) || isNaN(m) || isNaN(y))
return false;
if(((parseFloat(d) + "") != (parseInt(d, 10) + "")) || ((parseFloat(m) + "") != (parseInt(m, 10) + "")) || ((parseFloat(y) + "") != (parseInt(y, 10) + "")))
return false;
d = parseInt(d, 10);
m = parseInt(m, 10);
y = parseInt(y, 10);
if(d < 1 || m < 1 || y < 1)
return false;
if(m < 1 || m > 12)
return false;
if((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) && (d > 31))
return false;
if((m == 4 || m == 6 || m == 9 || m == 11) && (d > 30))
return false;
if((m == 2) && (d > 29))
return false;
if((m == 2) && (!isLeapYear(y)) && (d == 29))
return false;
return true;
}
function isLeapYear(year) // Check leap year
{
return ((year % 4 == 0 && year % 100 != 0) || ((year % 4 == 0 && year % 100 == 0) && (year % 400 == 0)));
}
Verifica di un indirizzo email
Per verificare se una stringa corrisponde ad un indirizzo email sintatticamente valido:
function isValidEmail(email)
{
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email);
}
Ottenere la posizione di un elemento: getElementPosition
La funzione riceve come parametro il riferimento all'oggetto - ricavato ad esempio mediante document.getElementById(object id) - e ne restituisce la posizione in pixel (top e left)
function getElementPosition(obj)
{
var t = 0;
var l = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
t += obj.offsetTop;
l += obj.offsetLeft;
obj = obj.offsetParent;
}
}
else if (obj.y && obj.x)
{
t += obj.y;
l += obj.x;
}
return {left : l, top : t};
}
Ottenere le dimensioni di un elemento: getElementSize
La funzione riceve come parametro il riferimento all'oggetto - ricavato ad esempio mediante document.getElementById(object id) - e ne restituisce le dimensioni in pixel (width e height)
function getElementSize(obj)
{
var w = obj.offsetWidth;
var h = obj.offsetHeight;
return {width : w, height : h};
}