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

Replace string 'a , b,c' to 'a, b, c' using regex

How can I convert this string

a   ,  b,c,d , e,  f

to:

a, b, c, d, e, f

I’m trying this regex but it doesn’t do what I expected:

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

str.replace(/(\w)|(?:[ \t]+),(\w)|(?:[ \t]+)/g, "$1, $2")

>Solution :

You may use it this way:

var str = 'a   ,  b,c,d , e,  f';
console.log( str.replace(/\s*,\s*/g, ', ') );
//=> a, b, c, d, e, f

Here pattern \s*,\s* searches for a comma surrounded with 0 or more whitespaces on either side and we replace it with , to get our desired output.

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