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.