Remove Whitespace-only Array Elements
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.
Another filter based variation - reusable (function)
function removeWhiteSpaceFromArray(array){
return array.filter((item) => item != ' ');
}
const words = ['spray', 'limit', 'elite', 'exuberant', ' ', ''];
const result = words.filter(word => word.trim().length > 0);
console.log(result);
a="remove white spaces"
a.split(' ').join('').split('');
It returns an array of all characters in {a="remove white spaces"} with no 'space' character.
You can test the output separately for each method: split() and join().