To split a string by comma and remove empty entries, go through the following steps:
split()
method and pass comma "," as a parameter to it. The split() method will return an array of substrings.filter()
method. Inside the callback function of the filter()
method, compare each element with an empty string.false
; otherwise, return true
.let food = 'Pizza,,Burger,Taco,Doughnut,,French Fries,'; let arr = food.split(','); console.log(arr); arr = arr.filter(element => { if(element === ""){ return false }else{ return true; } }); console.log(arr);
Output
["Pizza", "", "Burger", "Taco", "Doughnut", "", "French Fries", ""] ["Pizza", "Burger", "Taco", "Doughnut", "French Fries"]
The String.split() method splits a string based on the string or regular expression passed to it and returns an array of substrings.
Here, we want to split the string by comma, so we passed a comma to the split()
method.
let food = 'Pizza,Pasta,Burger,Taco'; console.log(str.split(",")); //["Pizza", "Pasta", "Burger", "Taco"]
It is important to understand that when there are no characters between commas, and you split the string by comma, you get empty entries.
let food = 'Pizza,,Burger,Taco,Doughnut,,French Fries,'; console.log(food.split(','));
Output
["Pizza", "", "Burger", "Taco", "Doughnut", "", "French Fries", ""]
The array filter() method creates a new array whose elements satisfy the specified condition. Inside the callback function, you specify the condition. When you want to include the element in a new array, return true
; otherwise, return false
.
We will use this logic to remove empty entries. In the callback function, check if an element is equal to an empty string or not. Return false
if an element is an empty string; otherwise, return true
.
arr = arr.filter(element => { if(element === ""){ return false }else{ return true; } });