Javascript – Retirando espaços de string (função trim)

by Luiz Paulo | dezembro 4, 2008 | 5 Comments »

Veja abaixo algumas soluções para retirar espaços do início e final de strings.

Exemplos simples

Exemplo curto (funções com expressão regular):

//trim completo
	function trim(str) {
		return str.replace(/^\s+|\s+$/g,"");
	}
 
	//left trim
	function ltrim(str) {
		return str.replace(/^\s+/,"");
	}
 
	//right trim
	function rtrim(str) {
		return str.replace(/\s+$/,"");
	}
 
	alert(trim("           TEXTO          "));

Exemplo curto (métodos da string com expressão regular):
Essa solução é bem mais elegante!

	//trim completo
	String.prototype.trim = function () {
		return this.replace(/^\s+|\s+$/g,"");
	}
 
	//left trim
	String.prototype.ltrim = function () {
		return this.replace(/^\s+/,"");
	}
 
	//right trim
	String.prototype.rtrim = function () {
		return this.replace(/\s+$/,"");
	}
	alert("           TEXTO          ".trim());

Outras soluções

Exemplo longo

	function trim (str)
	{
		var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
		for (var i = 0; i < str.length; i++) 		{ 			if (whitespace.indexOf(str.charAt(i)) == -1) 			{ 				str = str.substring(i); 				break; 			} 		} 		for (i = str.length - 1; i >= 0; i--)
		{
			if (whitespace.indexOf(str.charAt(i)) == -1)
			{
				str = str.substring(0, i + 1);
				break;
			}
		}
	    return whitespace.indexOf(str.charAt(0)) == -1 ? str : '';
	}

Outro exemplo

	function isWhitespace(charToCheck) {
		var whitespaceChars = " \t\n\r\f";
		return (whitespaceChars.indexOf(charToCheck) != -1);
	}
 
	//left trim
	function ltrim(str) {
		for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++); 		return str.substring(k, str.length); 	} 	//right trim 	function rtrim(str) { 		for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
		return str.substring(0,j+1);
	}
 
	//trim completo
	function trim(str) {
		return ltrim(rtrim(str));
	}

Caso queira se aprofundar no assunto, aconselho a leitura do artigo Faster JavaScript Trim que mostra vários testes de performance no IE e FF.

Façam bom proveito!

Categorias: Desenvolvimento web, JavaScript, Linguagens
Tags: , , , ,


 

Sobre

Foto Luiz Paulo

Sou desenvolvedor web desde 2000, atuei em grandes projetos web2.0. Atualmente trabalho na Automatos junto equipe de site desenvolvendo projetos web2.0 e utilizando como server-side a linguagem java.

Para saber mais sobre mim, acesse Meus Links ›


Valid XHTML 1.0 Strict Valid CSS!

Luiz Paulo | tecnologia web