Home > OS >  How can I use a for loop to delete empty spaces at the left and right of a string in JavaScript?
How can I use a for loop to delete empty spaces at the left and right of a string in JavaScript?

Time:10-11

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related