Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with regexp replacing every second comma in the string

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

like image 563
michael duvall Avatar asked May 20 '09 18:05

michael duvall


People also ask

How does. replace work in regex?

replace() The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How to use regex to replace string in c#?

RegularExpressions; public class Example { public static void Main() { string input = "This is text with far too much " + "white space."; string pattern = "\\s+"; string replacement = " "; string result = Regex. Replace(input, pattern, replacement); Console. WriteLine("Original String: {0}", input); Console.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does comma do in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set.


1 Answers

'1235, 3, 1343, 5, 1234, 1'.replace(/([0-9]+),\s([0-9]+),\s/g, '$1, $2; ')
like image 151
Dmitri Farkov Avatar answered Oct 31 '22 01:10

Dmitri Farkov