Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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]{2,}$/) !== null) src.splice(i, 1);

}

Error:

Uncaught TypeError: Cannot call method 'match' of undefined

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
287 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...