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());












