Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Whitespace-only Array Elements

Tags:

javascript

Since using array.splice modifies the array in-place, how can I remove all whitespace-only elements from an array without throwing an error? With PHP we have preg_grep but I am lost as to how and do this correctly in JS.

The following will not work because of above reason:

for (var i=0, l=src.length; i<l; i++) {

    if (src[i].match(/^[\s\t]{2,}$/) !== null) src.splice(i, 1);

}

Error:

Uncaught TypeError: Cannot call method 'match' of undefined

like image 346
tenub Avatar asked Dec 18 '13 21:12

tenub


People also ask

How do you remove white spaces from an array in Java?

To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e. Program: Java.

How do you trim an array?

To trim all strings in an array:Use the map() method to iterate over the array and call the trim() method on each array element. The map method will return a new array, containing only strings with the whitespace from both ends removed.

Does JSON Stringify remove white spaces?

JSON. stringify(body) returns it without spaces. Did you try to see if there are spaces before trying to remove it from there?


1 Answers

A better way to "remove whitespace-only elements from an array".

var array = ['1', ' ', 'c'];

array = array.filter(function(str) {
    return /\S/.test(str);
});

Explanation:

Array.prototype.filter returns a new array, containing only the elements for which the function returns true (or a truthy value).

/\S/ is a regex that matches a non-whitespace character. /\S/.test(str) returns whether str has a non-whitespace character.

like image 126
Paul Draper Avatar answered Sep 28 '22 12:09

Paul Draper