javascriptfor-loopstring-iteration

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.


Solution

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