Steve
Steve

Reputation: 31

How to replace each field delimiter of a delimited string (e.g. comma to semicolon) using regex and javascript?

I would like to replace every other comma in a string with a semicolon.

For example:

1,2,3,4,5,6,7,8,9,10

would become

1;2,3;4,5;6,7;8,9;10

What would be the regexp to do this? An explanation would be great.

Thank you :)

Upvotes: 2

Views: 4975

Answers (5)

Chris Pickett
Chris Pickett

Reputation: 2822

A non-regex answer:

function alternateDelims(array, delim_one, delim_two) {
    var delim = delim_one,
        len = array.length,
        result = [];

    for(var i = 0; i < len; i += 1) {
        result.push(array[i]);
        if(i < len-1) { result.push(delim); }
        delim = (delim === delim_one) ? delim_two : delim_one;
    }

    return result.join('');
}

nums = "1,2,3,4,5,6,7,8,9,10"
alternateDelims(nums.split(','), ';', ',');

Upvotes: 0

Colin
Colin

Reputation: 143

You could use this regex pattern

([^,]*),([^,]*),?

And replace with $1;$2,. The question mark on the end is to account for the lack of a comma signaling the end of the last pair.

For example...

var theString = "1,2,3,4,5,6,7,8,9,10";
theString = theString.replace(/([^,]*),([^,]*),?/ig, "$1;$2,"); //returns "1;2,3;4,5;6,7;8,9;10,"
theString = theString.substring(0, theString.length - 1); //returns "1;2,3;4,5;6,7;8,9;10"

Upvotes: 0

Paul
Paul

Reputation: 141917

var str = '1,2,3,4,5,6,7,8,9,10';
str.replace(/,(.*?,)?/g, ';$1');

// Now str === "1;2,3;4,5;6,7;8,9;10"

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78580

var myNums = "1,2,3,4,5,6,7,8,9,10";
myNums.replace(/(.*?),(.*?,)?/g,"$1;$2");

That'll do it.

Upvotes: 4

Tejs
Tejs

Reputation: 41256

You would do something like this:

 myString.replace(/,/g, ';');

Upvotes: 0

Related Questions