Regex to add a space after each comma in Javascript

前端 未结 8 1455
我寻月下人不归
我寻月下人不归 2021-02-05 10:39

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条回答
  •  臣服心动
    2021-02-05 11:28

    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!
    

提交回复
热议问题