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:
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.