Trim, LTrim y RTrim en Javascript

1
1317

Trim es una Funcion y/o Metodo muy conocido en distintos lenguajes de programacion, esta funcion realiza el corte de espacios en blanco de los extremos de una cadena,esta funcion extiende tambien a ltrim(left trim) y rtrim(right trim). En Javascript no vienen incorporado, es por eso que veremos la manera de implementarlo, una forma es como un metodo para los tipo String y la otra es como una simple funcion(stand-alone).

Javascript Trim como metodos

String.prototype.trim = function() {
	return this.replace(/^s+|s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/s+$/,"");
}
// ejemplo trim, ltrim y rtrim
var cad = "  Metodo trim(),ltrim(),rtrim() ";
alert("*" + cad.trim() + "*");
alert("*" + cad.ltrim() + "*");
alert("*" + cad.rtrim() + "*");

Javascript Trim como funciones Stand-Alone

function trim(cad)
{
	return cad.replace(/^s+|s+$/g,"");
}
function ltrim(cad)
{
	return cad.replace(/^s+/,"");
}
function rtrim(cad)
{
	return cad.replace(/s+$/,"");
}
// ejemplo trim, ltrim y rtrim
var cad = " funciones trim,ltrim,rtrim  ";
alert("*" + trim(cad) + "*");
alert("*" + ltrim(cad) + "*");
alert("*" + rtrim(cad) + "*");

Compatibilidad

Las funciones anteriormente explicadas hacen el uso de expresiones regulares, que son compatibles con JavaScript 1.2 + o JScript 3.0 +. Si se requiere funciones para versiones antiguas de Javascript 1.0, aqui dejo las funciones compatibles para antiguas versiones.

function ltrim(str)
{
	var k = 0;
	for(k = 0; k < str.length && isSpace(str.charAt(k)); k++);
	return str.substring(k, str.length);
}
function rtrim(str)
{
	var j=str.length-1
	for(j=str.length-1; j>=0 && isSpace(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}
function trim(str)
{
	return ltrim(rtrim(str));
}
function isSpace(charToCheck)
{
	var whitespaceChars = " tnrf";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here