Reputation: 573
I need to have a regular expression that replaces commas and spaces with a comma and a space, but leaves it alone if it's already a comma and a space in sequence.
Example:
44,55 90 should turn into 44, 55, 90
but, 44, 55, 90 when entered again should remain the same.
I initially tried /[\s,]/g
but it of course replaces any comma or space with both a comma and space, so 44, 55, 90 became 44, , 55, , 90
Upvotes: 0
Views: 371
Reputation: 1865
The answer is very simple / ,?|,/g
Or if you want to remove any amount of white space before comma / *,?| /g
Or if you want go crazy go with this /\s*,\s*|\s+/g
this will replace any extra spacing before , and after it and do all good stuf as erlier.
Upvotes: 2
Reputation: 6958
This will work for the test string, assuming you're looking to fix strings with digits, commas and spaces, and not other combinations of characters.
Search for this:
\d(,)\d|\d([ ]{1,},[ ]{0,})\d|\d([ ]{1,})\d
Replace capture group 1 with comma ,
and a space, .
That should handle any real or potential white space with quantifiers checking for multiple whitespaces.
44,55 90 ,44 , 55 , 90 , 1234 ,
Upvotes: 0
Reputation: 1061
You could go the other way and replace everything that is not digits with anything you want, using a negated character class:
'999 123,098b7b7b7b7b,,,123^&*()43'.replace(/[^\d]+/g,', ');
//"999, 123, 098, 7, 7, 7, 7, 123, 43"
Upvotes: 0