简体   繁体   中英

Removing empty strings from array (Regex) - Javascript

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() .

I need this portion of the code to remove all whitespace and empty strings, but the lines...

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 variable i to allow for the missing element - or, simpler, loop backwards.

for(i = inputArr.length - 1; i >= 0; i--) {
    if(accountsBool) {
        inputArr[i] = inputArr[i].replace(/\s/g,"");
        if (inputArr[i] === "") {
            inputArr.splice(i,1);
        }
    }
}

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:

for(i = inputArr.length - 1; i >= 0; i--) {
    if(accountsBool) {
        if (!/[^\s]/.test(inputArr[i])) {
            inputArr.splice(i,1);
        }
    }
}

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.

String.split() splits string into an array which you treat like a string later. You can use replace function instead of split:

inputArr[i] = inputArr[i].replace(/\s+/g, '');

Then:

if (inputArr[i] == "") {
    inputArr.splice(i,1);
}

If you replace

inputArr[i] = inputArr[i].split(/\s+/);

with

inputArr[i] = inputArr[i].replace(/\s/g,'');

that should fix one issue.

Also, !inputArr[i].match(/[^\\s]/) is redundant since you already removed all whitespace from that input array value.

Last, you need to decrement your index when you splice your array, or iterate in reverse order.

Here's a working fiddle to test.

You need another loop inside the loop you describe that will go through the array produced by the split method. As commenters said, match is not possible with an array. So something like:

for (var i = 0; i < inputArr.length; i++) {
    if(accountsBool) {
        inputArr[i] = inputArr[i].split(/\s+/); // produces an array
        for (var j = 0; j < inputArr[i].length; j++) {
            if (inputArr[i][j] === "" || !inputArr[i][j].match(/[\S]/)) { // check each string in the array for empty or space
                // inputArr.splice(i,1);
            }
        }
    }
}

Also the [^\\s] part of RegEx can be rewritten [\\S] , as above.

But it's not entirely clear what you are trying to do with splice (hence I've commented it out above). If you are trying to just get rid of all space in the strings altogether, then your code could be far simpler -- you just need to use the replace method.

If you are trying to get rid of excessive whitespace, again your code could be far simpler: just use replace on each string with the /\\s+/ as your RegEx search pattern and ' ' as your replacement. Empty strings can be removed afterwards with the simple conditional check you already have...

for (var i = 0; i < inputArr.length; i += 1) {
    if (accountsBool) {
        inputArr[i] = inputArr[i].replace(/\s+/, ' '); // replaces all multiple spaces with one space
        if (!inputArr[i]) { // check each string in the array for empty or space
                inputArr.splice(i,1);
        }
    }
}

This will leave you with strings where there are spaces between words, for example, but never more than one space (eg, it should get rid of double-spacing and tab-spacing).

Use a .filter() on the array if you want to remove entries that are empty strings or only whitespace.

inputArr = inputArr.filter(function(item) {
    return accountsBool && Boolean(item.trim())
});

Note the following:

  • this replaces the old array with a new one
  • you'll need a shim for .filter() for old browsers
  • you'll need a shim for .trim() for old browsers
    • you can use item.replace(/^\\s+|\\s+$/g, "") instead of item.trim()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM