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?
8 Answers
Simplest Solution
"1,2,3,4".replace(/,/g, ', ')
//-> '1, 2, 3, 4'
Another Solution
"1,2,3,4".split(',').join(', ')
//-> '1, 2, 3, 4'
2 Comments
user33192
What if there are multiple spaces after comma? like "1, 2,3,4" or "1, 2,3,4". It works when there is no space after comma but if single or multiple comma already exists, it will add additional space to existing space. I think, we don't want that.
kzh
Just update the RegExp to you needs:
.replace(/ *, */g, ', ')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.
1 Comment
TechFreak
This is wrong. It removes 's' from your string. Try This: "s1,s2,s3,s4,s5".replace(/,[s]*/g, ", ")
Use String.replace with a regexp.
> var input = '1,2,3,4,5',
output = input.replace(/(\d+,)/g, '$1 ');
> output
"1, 2, 3, 4, 5"
4 Comments
Bryan Oakley
why such a complicated pattern for this task? Why not just replace ',' with ', '? Perhaps a better pattern would do a lookahead and only replace commas that don't already have a space after them.
Matt Ball
There are many ways to skin this cat. Yes,
input.replace(/,/g, ', ') would also work. Does it really matter?Bryan Oakley
Does it matter? I think it does. When teaching someone how to program we should teach them to strive for the simplest solution.
Gareth
When I have 2 regular expressions to check, I look for the differences. In this case: What if there isn't a digit in front of one of the commas? What if there is a comma at the start of the string, or two commas next to each other? If those cases will never happen, or you don't care what happens in those cases, then there's no need to use the more complicated version
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!
Comments
var numsStr = "1,2,3,4,5,6";
var regExpWay = numStr.replace(/,/g,", ");
var splitWay = numStr.split(",").join(", ");
1 Comment
Jeevan Takhar
The split and join method is the faster of the two in this case. You can run a test on the speed difference here: jsperf.com/replace-vs-split-join/6
gflag).