How to remove spaces before and after a string without the Javascript "Trim()" method

Asked

Viewed 582 times

1

I have this code to remove the first and last spaces but it’s removing all the spaces present.

Follows:

const separador = ' ';

function filtro(separador, str) {
  let resultado = '';
  let stringNova = '';
  for (let i = 0; i < str.length; i++) {
    if (str[i] === separador) {
      resultado += str[i];
    } else {
        stringNova += str[i];
    }
  }

  return stringNova;
}


console.log(filtro(separador, ("  X DSA   ")));

Should return:

X DSA and not XDSA.

Someone could help me ?

Guys, I’m actually creating a trim method of my own, so I don’t want to use the trim method of the JS itself

  • +1 for several reasons

3 answers

6

I see no need to reinvent the wheel, the Javascript already has a native function to accomplish this and it is already "approved" and tested.

Below is an example with method Trim():

console.log(("  X DSA   ").trim());

  • 2

    +1 for several reasons

  • +1 also, following the principles of the great Uncle Bob! D

5

You can use the regex:

/^\s+|\s+$

Where:

  • ^ identifies the beginning of the text
  • \s identifies spaces
  • | or
  • $ end of text

Example

function fazerTrim(string) {
  return string.replace(/^\s+|\s+$/g, "");
}

console.log(fazerTrim("  X DSA   "));

2


By your idea would need to stop the going when finding the "first nonseparator" and start a new one backwards, following the same idea.

I got carried away doing it here.. see if this meets :P

function MeuTrim(pTexto){
    var letra = pTexto[0];

    if (pTexto.length > 0){
        while (letra == ''){
            if (pTexto.length == 1)
                pTexto = '';

            pTexto = pTexto.substr(1);
            letra = pTexto[0];
        }

        if (pTexto.length > 0){
            letra = pTexto[pTexto.length - 1];
            while (letra == ''){
                if (pTexto.length == 1)
                    pTexto = '';

                pTexto = pTexto.substr(0, pTexto.length - 2);
                letra = pTexto[pTexto.length - 1];
            }
        }
    }

    return pTexto;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.