How to remove spaces before and after a string without the JavaScript Trim method

2

I have this code to remove the first and last spaces but it is removing all the spaces present. Following:

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 .

Could someone help me?

Personal, in real I am creating a Trim method myself, so I do not want to use the Trim method of JS itself     

asked by anonymous 02.02.2018 / 18:00

3 answers

2

For your idea, you should stop the for when you find the "first non-separator" and start a new one backwards, following the same idea.

I got excited doing it here .. see if that catches: 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;
}
    
02.02.2018 / 18:51
7

You can use 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   "));
    
02.02.2018 / 18:06
3

I do not see the need to reinvent the wheel, the Javascript already has a native function to do this and it is already "homologated" and tested.

Here's an example with trim () method:

console.log(("  X DSA   ").trim());
    
02.02.2018 / 18:06