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!
Posts Relacionados
Categorias: Desenvolvimento web, JavaScript, Linguagens
Tags: , code, example, javascript, trim




![[Costão do Santinho] Guardião](http://farm5.static.flickr.com/4122/4820659063_e4573c17c9_s.jpg)
![[Costão do Santinho] Praia](http://farm5.static.flickr.com/4135/4821276850_048c3d09d8_s.jpg)

