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
To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e. Program: Java.
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.
JSON. stringify(body) returns it without spaces. Did you try to see if there are spaces before trying to remove it from there?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With