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








5 Comentários
Muito legal essa história de
trim, e muito bem citado o artigo «Faster JavaScript Trim».Aliás o
trimmais bonito citado aqui é um dos menos eficientes, enquanto os exemplos longos são os mais eficientes.Peculiaridades de Javascript, vai entender...
Em Python string possui o método
strip:Em Lua é preciso fazer uma função:
Daí é só usar:
Em Common Lisp é feio pacas:
Em C é preciso usar uma combinação das funções
rindex,indexestrcat, todas do cabeçalhostring.h. Não é complicado, se der vontade depois eu posto.Em C++, não sei se dá para fazer mais simples, mas usando os métodos de
std::stringé bem fácil.Em Objective-C a classe NSString possui o método
-stringByTrimmingSpaces.Em Smalltalk a class String possui o método
trimBlanks.Esqueci alguma? =)
[]'s
Cacilhas
Sim Cacilhas,
Essa da função maior ser mais eficiente não dá para entender. Por isso coloquei a referência para quem queira mais informações.
E por isso não coloquei o código grande como "Exemplos Criativos", como coloquei no post: Javascript - Último dia do mês.
[]'s
Shell script!
[]'s
ANSI C:
Então o Cacilhas é o almanaque das linguagens de programação.
Em vez de perguntar ao google agora vai ser pergunte ao cacilhas
Brincadeira.