Help with regexp replacing every second comma in the string

前端 未结 6 525
暖寄归人
暖寄归人 2020-12-19 04:36

I have a string of that displays like this....

1235, 3, 1343, 5, 1234, 1

I need to replace every second comma with a semicolon

i.e.

1235, 3;

相关标签:
6条回答
  • 2020-12-19 05:13
    var s='1235, 3, 1343, 5, 1234, 1';
    
    s=s.replace(/([^,]+,[^,]+),/g,'$1;')
    

    match anything that is not a comma, followed by a comma, followed by anything that is not a comma, and a comma.

    replace everthing inside the parens (which doesn't include the last comma) with itself ('$1'), and add a semicolon in place of that comma.

    0 讨论(0)
  • 2020-12-19 05:14
    var myregexp = /(\d+,\s\d+),/g;
    result = subject.replace(myregexp, "$1;");
    
    0 讨论(0)
  • 2020-12-19 05:15
    var s = '1235, 3, 1343, 5, 1234, 1';
    var result = s.replace(/(,[^,]*),/g,"$1;");
    
    0 讨论(0)
  • 2020-12-19 05:16

    var foo = "1235,3,1343,5,1234,1".replace(/(.\*?),(.\*?),/g, "$1,$2;");
    
    console.log(foo)

    0 讨论(0)
  • 2020-12-19 05:26

    How about:

    var regex = /(\d+),\s(\d+),\s/g;
    var str = '1235, 3, 1343, 5, 1234, 1'; 
    alert(str.replace(regex, '$1, $2; ')); // 1235, 3; 1343, 5; 1234, 1
    
    0 讨论(0)
  • 2020-12-19 05:30
    '1235, 3, 1343, 5, 1234, 1'.replace(/([0-9]+),\s([0-9]+),\s/g, '$1, $2; ')
    
    0 讨论(0)
提交回复
热议问题