Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

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

A com­mon case in many sit­u­a­tions is to split user input on either a comma or a space.

Quick answer


The above code splits the string even if there are mul­ti­ple spaces or com­mas consecutively.


The filter func­tion accepts a func­tion as an argu­ment and only adds ele­ments to the result array if the func­tion returns true.

In the case above, we pass the Boolean con­struc­tor as an argu­ment. This returns false for all the empty strings that occur as a result of con­sec­u­tive comma or spaces.Thats how you get an array of only the words you care about.

Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...