I have a string that is made up of a list of numbers, seperated by commas. How would I add a space after each comma using Regex?
I find important to note that if the comma is already followed by a space you don't want to add the space:
"1,2, 3,4,5".replace(/,(?=[^\s])/g, ", ");
> "1, 2, 3, 4, 5"
This regex checks the following character and only replaces if its no a space character.
Another simple generic solution for comma followed by n spaces:
"1,2, 3, 4,5".replace(/,[s]*/g, ", ");
> "1, 2, 3, 4, 5"
Always replace comma and n spaces by comma and one space.
Those are all good ways but in cases where the input is made by the user and you get a list like "1,2, 3,4, 5,6,7"
..In which case lets make it idiot proof! So accounting for the already formatted parts of the string, the solution:
"1,2, 3,4, 5,6,7".replace(/, /g, ",").replace(/,/g, ", ");
//result: "1, 2, 3, 4, 5, 6, 7" //Bingo!
var numsStr = "1,2,3,4,5,6";
var regExpWay = numStr.replace(/,/g,", ");
var splitWay = numStr.split(",").join(", ");
Don't use a regex for this, use split and join.
It's simpler and faster :)
'1,2,3,4,5,6'.split(',').join(', '); // '1, 2, 3, 4, 5, 6'
As I came here and did not find a good generic solution, here is how I did it:
"1,2, 3,4,5".replace(/,([^\s])/g, ", $1");
This replaces comma followed by anything but a space, line feed, tab... by a comma followed by a space.
So the regular expression is:
,([^\s])
and replaced by
, $1