I have the following code in my project:
for(i = 0; i < inputArr.length; i++) {
if(accountsBool) {
inputArr[i] = inputArr[i].split(/\s+/);
if (inputArr[i] == "" || !inputArr[i].match(/[^\s]/)) {
inputArr.splice(i,1);
}
}
}
I’ll try to explain the issue the best I can…
I need this portion of the code to remove all whitespace and empty strings, but the lines…
inputArr[i] = inputArr[i].split(/\s+/);
and…
if (inputArr[i] == "" || !inputArr[i].match(/[^\s]/)) {
inputArr.splice(i,1);
}
…don’t work together. I get the error, “Object doesn’t support this property or method”. If I comment out one and run the code with the other it seems to work fine. The syntax seems to be right too. Any ideas?
inputArr is an array of strings that is parsed in from a text area.
Thank you.
.split()returns an array, which doesn’t work with.match().You seem to be saying that items that don’t contain at least one non-whitespace character should be removed from the from the array, and any remaing items should be updated to have any whitespace removed (but keeping the other characters). If so, use
.replace()first to remove the whitespace, then test whether to remove the item.Note that if you use
.splice()in a loop you need to adjust your iterator variableito allow for the missing element – or, simpler, loop backwards.If you’re saying that items that don’t contain at least one non-whitespace character should be removed but you want to leave whitespace in place in the remaining elements then do this:
Note also that if you have no other processing in your loop then you should move the
if(accountsBool)test to immediately before the loop rather than doing it on every iteration.