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; 1343, 5; 1234, 1
the string length will always be different but will follow the same pattern as the above i.e. digits comma space digits comma space, etc.
how can I do this with javascript? Is it possible?
Thanks, Mike
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; 1343, 5; 1234, 1
the string length will always be different but will follow the same pattern as the above i.e. digits comma space digits comma space, etc.
how can I do this with javascript? Is it possible?
Thanks, Mike
Share Improve this question edited May 20, 2009 at 18:14 Motti 115k56 gold badges194 silver badges273 bronze badges asked May 20, 2009 at 18:12 michael duvallmichael duvall 831 silver badge4 bronze badges 1- 2 Thank you all very much, I have learned quite a bit from these examples. – michael duvall Commented May 21, 2009 at 15:07
6 Answers
Reset to default 8'1235, 3, 1343, 5, 1234, 1'.replace(/([0-9]+),\s([0-9]+),\s/g, '$1, $2; ')
var s = '1235, 3, 1343, 5, 1234, 1';
var result = s.replace(/(,[^,]*),/g,"$1;");
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.
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
var myregexp = /(\d+,\s\d+),/g;
result = subject.replace(myregexp, "$1;");
var foo = "1235,3,1343,5,1234,1".replace(/(.\*?),(.\*?),/g, "$1,$2;");
console.log(foo)