Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing a leading or trailing empty-string in a regex split

What is the most common way to deal with something such as the following?

const names = 'Harry Trump  ;Fred Barney; Helen Rigby ;   Bill Abel ;Chris Hand '
let re = /\s*(?:;|$)\s*/;
console.log(names.split(re));
// ["Harry Trump",  "Fred Barney",  "Helen Rigby",  "Bill Abel",  "Chris Hand",  ""]
//                                                                              ^^^^^

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Just add filter after split, something like this:

const names = 'Harry Trump  ;Fred Barney; Helen Rigby ;   Bill Abel ;Chris Hand '
let re = /\s*(?:;|$)\s*/;

console.log(names.split(re).filter(Boolean));
// ["Harry Trump",  "Fred Barney",  "Helen Rigby",  "Bill Abel",  "Chris Hand"]

Keep in mind that this will filter out any other negative values as well like null, undefined, false, 0 etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading