Al igual que Dustin Diaz tenía sus 10 mejores funciones en javascript, los chicos de hunlock tienen otras.
1. Trim()
Trim es una función que nos permite eliminar los carácteres en blanco al principio y fin de una cadena.
Código:String.prototype.trim = function() { //Trim ambas direcciones return this.replace(/^\s+|\s+$/g,""); } String.prototype.ltrim = function() { //Trim izquierda return this.replace(/^\s+/g,""); } String.prototype.rtrim = function() { //Trim Derecha return this.replace(/\s+$/g,""); }
Uso:var test = " Test "; var test1 = test.ltrim(); // returns "Test " var test2 = test.rtrim(); // returns " Test" var test3 = test.trim(); // returns "Test"
1. sortNum()
sortNum()
es una función que nos permite ordenar un array de forma numérica.
Código:Array.prototype.sortNum = function() { return this.sort( function (a,b) { return a-b; } ); }
Uso:var tmp = [5,9,12,18,56,1,10,42,30,7,97,53,33,35,27]; tmp=tmp.sortNum(); // returns 1,5,7,9,10,12,18,27,30,33,35,42,53,56,97
2. formatNumber()
formatNumber()
nos permite formatear la salida de un número al formato que queramos.
Código:
function formatNumber(num,prefix){
prefix = prefix || '';
num += '';
var splitStr = num.split('.');
var splitLeft = splitStr[0];
var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
var regx = /(\d+)(\d{3})/;
while (regx.test(splitLeft)) {
splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
}
return prefix + splitLeft + splitRight;
}
function unformatNumber(num) {
return num.replace(/([^0-9\.\-])/g,'')*1;
}
Uso:
var test1 = formatNumber('5123456789.25'); // returns 5,123,456,789.25
var test2 = formatNumber(1234.15,'$'); // returns $1,234.15
var test3 = unformatNumber('$1,234.15'); // returns 1234.15
3. Array.find()
find()
como una extensión del objeto array, nos permite realizar una busqueda en nuestros arrays.
Código:Array.prototype.find = function(searchStr) { var returnArray = false; for (i=0; i<this.length; i++) { if (typeof(searchStr) == 'function') { if (searchStr.test(this[i])) { if (!returnArray) { returnArray = [] } returnArray.push(i); } } else { if (this[i]===searchStr) { if (!returnArray) { returnArray = [] } returnArray.push(i); } } } return returnArray; }
Uso:var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble']; // 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20 var thirty=tmp.find(30); // Returns 9, 14, 17 var thirtyfive=tmp.find('35'); // Returns 18 var thirtyfive=tmp.find(35); // Returns 15 var haveBlue=tmp.find('blue'); // Returns 8 var notFound=tmp.find('not there!'); // Returns false var regexp1=tmp.find(/^b/); // returns 8,20 (first letter starts with b) var regexp1=tmp.find(/^b/i); // returns 8,19,20 (same as above but ignore case)
4.htmlEntities() y stripTags()
Versión en javascript de esta función de PHP con el mismo nombre, que te convierte los tags HTML a carácteres carácteres imprimibles.
Código:String.prototype.htmlEntities = function () { return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); };
Uso:var tmp = '<html><head></head>'; var safe= tmp.htmlEntities(); // Returns
<html><head></head>
Tampoco podía faltar stripTags() que nos elimina las etiquetas HTML de nuestros textos.
Código:String.prototype.stripTags = function () { return this.replace(/<([^>]+)>/g,''); }
Uso:var tmp = '<a href="htpp://somespammer.com">Some Link</a>'; var safe= tmp.stripTags(); // Returns
Some Link;
5.isArray()
isArray()
nos devuelve true si se trata de un array.
Código:function isArray(testObject) { return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number'; }
Uso:var tmp = [5,9,12,18,'blue',30,7,97,53,33,30,35,27,30]; var tmp2 = {0:5,1:9,2:12} test1 = isArray(tmp); // returns true test2 = isArray(tmp2); // returns false;
Tambien podemos ampliar la funcionalidad de Array con prototype
y añadirle este método a los que ya tiene.
Código:Object.prototype.isArray = function() { return this.constructor == Array; }
Uso:alert( [].isArray() ); // true alert( {}.isArray() ); // false
6. Cookies()
Ver más info aqui
7.map()
Map()
es una función que nos permite hacer pasar una función determinada a todos los elementos de un array()
.
Código:Array.prototype.map = function(f) { var returnArray=[]; for (i=0; i<this.length; i++) { returnArray.push(f(this[i])); } return returnArray; }
Uso:function trim(str) { return str.replace(/^\s+|\s+$/g,''); } var tmp = ['now', 'is', ' the ', 'time ', ' for ', ' all', ' good ', ' men ']; var test = tmp.map(trim); // returns now,is,the,time,for,all,good,men
8.getCSSRule(), killCSSRule(), addCSSRule()
Se trata de un paquete de funciones que nos ayudan a manejar las hojas de estilos css de una forma más cómoda.
Código:function getCSSRule(ruleName, deleteFlag) { if (document.styleSheets) { for (var i=0; i<document.styleSheets.length; i++) { var styleSheet=document.styleSheets[i]; var ii=0; var cssRule=false; do { if (styleSheet.cssRules) { cssRule = styleSheet.cssRules[ii]; } else { cssRule = styleSheet.rules[ii]; } if (cssRule) { if (cssRule.selectorText==ruleName) { if (deleteFlag=='delete') { if (styleSheet.cssRules) { styleSheet.deleteRule(ii); } else { styleSheet.removeRule(ii); } return true; } else { return cssRule; } } } ii++; } while (cssRule) } } return false; } function killCSSRule(ruleName) { return getCSSRule(ruleName,'delete'); } function addCSSRule(ruleName) { if (document.styleSheets) { if (!getCSSRule(ruleName)) { if (document.styleSheets[0].addRule) { document.styleSheets[0].addRule(ruleName, null,0); } else { document.styleSheets[0].insertRule(ruleName+' { }', 0); } } } return getCSSRule(ruleName); }
Uso:// devuelve el objeto para la clase "fancyStyle" fancyStyleObject=getCSSRule('fancyStyle'); // aplica la propiedad underline a la decoración del texto del objeto anterior fancyStyleObject.style.textDecoration='underline' // Elimina la clase "fancyStyle" eliminado los estilos aplicados al objeto. killCSSRule('fancyStyle'); // Crea un nueva regla stylesheet para los parrafos. newStyle=addCSSRule('p'); // Cambia todos los parrafos anteriores al color azul. newStyle.style.color='blue'; // Creamos una nueva CSS class llamada fancyStyle. newStyle=addCSSRule('.fancyStyle'); // Aplicamos un fondo verde a todos los elementos con la clase fancyStyle. newStyle.backgroundColor='green';
9.getElementByClassName()
Ver más info aqui.
10. ajaxObject()
Quizas la función que más ha revolucionado el javascript moderno, esta función ha abierto un abanico de posibilidades en un mundo de validaciones de formularios. Se trata de una función que hace posible la interacción del cliente con el servidor sin necesidad de recargar la página.
Código:function ajaxObject(url, callbackFunction) { var that=this; this.updating = false; this.update = function(passData,postMethod) { if (that.updating==true) { return false; } that.updating=true; var AJAX = null; if (window.XMLHttpRequest) { AJAX=new XMLHttpRequest(); } else { AJAX=new ActiveXObject("Microsoft.XMLHTTP"); } if (AJAX==null) { return false; } else { AJAX.onreadystatechange = function() { if (AJAX.readyState==4) { that.updating=false; that.callback(AJAX.responseText,AJAX.status,AJAX.responseXML); delete AJAX; } } var timestamp = new Date(); if (postMethod=='POST') { var uri=urlCall+'?'+timestamp.getTime(); AJAX.open("POST", uri, true); AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); AJAX.send(passData); } else { var uri=urlCall+'?'+passData+'×tamp='+(timestamp*1); AJAX.open("GET", uri, true); AJAX.send(null); } return true; } } var urlCall = url; this.callback = callbackFunction || function () { }; }
Uso:// Función que recibe la respuesta del servidor- function fin(responseTxt,responseStat) { alert(responseStat+' - '+responseTxt); } //Creamos el objeto ajax(test1) y le indicamos la ruta que ha de seguir para obtener los datos // que se procesarán en la función fin(). var test1 = new ajaxObject('http://someurl.com/server.cgi',fin); test1.update(); // Pasamos id=user4379 como parametro a la página indicada. var test2 = new ajaxObject('http://someurl.com/program.php',fin); test2.update('id=user4379'); // create a new ajaxObject but we'll overwrite the callback function inside // the object to more tightly bind the object with the response hanlder. var test3 = new ajaxObject('http://someurl.com/prog.py', fin); test3.callback = function (responseTxt, responseStat) { // we'll do something to process the data here. document.getElementById('someDiv').innerHTML=responseTxt; } test3.update('coolData=47&userId=user49&log=true'); // create a new ajaxObject and pass the data to the server (in update) as // a POST method instead of a GET method. var test4 = new ajaxObject('http://someurl.com/postit.cgi', fin); test4.update('coolData=47&userId=user49&log=true','POST');
4 comentarios, 1 referencias
+
#