Be the first user to complete this post

  • 0
Add to List

Split a string in javascript when both comma and spaces are present

A common case in many situations is to split user input on either a comma or a space.

Quick answer

yourString.split(/s*[s,]s*/).filter(Boolean);
The above code splits the string even if there are multiple spaces or commas consecutively.

Explanation

The filter function accepts a function as an argument and only adds elements to the result array if the function returns true. In the case above, we pass the Boolean constructor as an argument. This returns false for all the empty strings that occur as a result of consecutive comma or spaces.Thats how you get an array of only the words you care about.



Also Read:

  1. The JavaScript Prototype Property - Visualized
  2. Getting started with localStorage vs sessionStorage in html5
  3. css - align text to an image vertically
  4. Getting started with automation testing for webrtc applications
  5. Passing arguments from one function to another in javascript