Julio Rodríguez
Julio Rodríguez

Reputation: 477

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.

Upvotes: 0

Views: 1227

Answers (3)

Zac
Zac

Reputation: 1532

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

Upvotes: 1

paliz
paliz

Reputation: 353

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370819

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

Upvotes: 3

Related Questions