Shealan
Shealan

Reputation: 1346

Regex to add a space after each comma in Javascript

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?

Upvotes: 29

Views: 43655

Answers (8)

Daniel R Guzman
Daniel R Guzman

Reputation: 61

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!

Upvotes: 6

user3375803
user3375803

Reputation: 149

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.

Upvotes: 12

Benoit Thiery
Benoit Thiery

Reputation: 6387

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

Upvotes: 2

eliocs
eliocs

Reputation: 18827

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.

Upvotes: 28

kzh
kzh

Reputation: 20638

Simplest Solution

"1,2,3,4".replace(/,/g, ', ')
//-> '1, 2, 3, 4'

Another Solution

"1,2,3,4".split(',').join(', ')
//-> '1, 2, 3, 4'

Upvotes: 39

Martin Jespersen
Martin Jespersen

Reputation: 26193

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'

Upvotes: 3

epascarello
epascarello

Reputation: 207557

var numsStr = "1,2,3,4,5,6";
var regExpWay = numStr.replace(/,/g,", ");
var splitWay = numStr.split(",").join(", ");

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 360066

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"

Upvotes: 7

Related Questions