Javascript – Retirando espaços de string (função trim)
Postado por: Luiz Paulo emVeja 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 = 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 =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.














Trim entrou no javascript 1.8 que entrou no Firefox 3.5
http://developer.mozilla.org/en/firefox_3.5_for_developers