Remove Whitespace-only Array Elements

后端 未结 8 916
悲&欢浪女
悲&欢浪女 2020-12-08 17:30

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

8条回答
  •  长情又很酷
    2020-12-08 18:01

    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.

提交回复
热议问题