Regex to add a space after each comma in Javascript

前端 未结 8 1456
我寻月下人不归
我寻月下人不归 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:19

    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.

    0 讨论(0)
  • 2021-02-05 11:26

    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.

    0 讨论(0)
  • 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!
    
    0 讨论(0)
  • 2021-02-05 11:29
    var numsStr = "1,2,3,4,5,6";
    var regExpWay = numStr.replace(/,/g,", ");
    var splitWay = numStr.split(",").join(", ");
    
    0 讨论(0)
  • 2021-02-05 11:29

    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'
    
    0 讨论(0)
  • 2021-02-05 11:32

    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
    
    0 讨论(0)
提交回复
热议问题