Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript - Remove Whitespace-only Array Elements

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...