Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
How can I use a for loop to delete empty spaces at the left and right of a string in JavaScript?

I'm trying to make a homemade trim()'s JavaScript method. I mean, what I want to do can be achieved using trim(): to delete all white spaces from the left and right of the string.

I came up with this cumbersome solution; I think it should work, but it's not working at all; instead, it is removing all elements of the string array and leaving just an array of strings with one empty space as the unique element.

Here is a running snippet of the code I did:

const stringWithManyWhiteSpaces = '        I like ants... Remember us   ';

const charArray = [...stringWithManyWhiteSpaces];

function killLeftToRight(charArr) {
    for ( let i = 0; i < charArr.length; i++) {
        if (charArr[i] === ' ') {
            charArr.splice(i + 1);
        } else {
             break;
        }
    }
}

function killRightToLeft(charArr) {
    for ( let i = charArr.length -1; i >= 0; i--) {
        if (charArr[i] === ' ') {
            charArr.splice(i + 1);
        } else {
            break;
        }
    }
}

function myTrim(){
  killRightToLeft(charArray)
  killLeftToRight(charArray);
  console.log(charArray)
}

myTrim();

May anyone let me figure out what's wrong with my code? Thank you so much.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

  • To remove items from an array, splice requires you to specify how many to remove, in the second argument
  • splice will remove the item at the given index from the array, so on the next iteration, if you're iterating through indicies in ascending order, you may "skip" an item, due to its index having just been re-calculated

Easier to use .pop (remove from end) and .shift (remove from beginning).

const stringWithManyWhiteSpaces = '        I like ants... Remember us   ';

function killLeftToRight(charArr) {
    while (charArr[0] === ' ') {
        charArr.shift();
    }
}

function killRightToLeft(charArr) {
    while (charArr[charArr.length - 1] === ' ') {
        charArr.pop();
    }
}

function myTrim(str){
  const charArray = [...str];
  killRightToLeft(charArray);
  killLeftToRight(charArray);
  console.log(charArray.join(''));
}

myTrim(stringWithManyWhiteSpaces);

about 4 years ago · Juan Pablo Isaza Relatório

0

your approach can be changed in different ways so it would work fine as mentioned in the previous answer, but if your target is to have your own implementation for trimming, what about implementing it in a simpler way?:

const stringWithManyWhiteSpaces = `        


I like ants... Remember us   


   `;

function trimMe(stringToTrim) {
  return stringToTrim.replace(/^[\s\n]+|[\s\n]+$/g, '')
}

console.log(trimMe(stringWithManyWhiteSpaces));

about 4 years ago · Juan Pablo Isaza Relatório

0

all you need for remove white space is string.trim()

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda