I would like to replace every other ma in a string with a semicolon.
For example:
1,2,3,4,5,6,7,8,9,10
would bee
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 :)
I would like to replace every other ma in a string with a semicolon.
For example:
1,2,3,4,5,6,7,8,9,10
would bee
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 :)
Share Improve this question edited Aug 23, 2011 at 17:51 Brian 13.6k11 gold badges59 silver badges83 bronze badges asked Aug 22, 2011 at 21:51 SteveSteve 311 silver badge2 bronze badges 3- Your example replaces all mas. But you seem to suggest in the question that some mas should not be replaced. – Dunes Commented Aug 22, 2011 at 21:56
- Your question is very unclear. You mention that you want to replace the first pair (two) mas, but then mention the first ma (one). Your example then shows all mas being replaced with a semicolon. I remend you update your example to reflect the initial data as well as the proper result to remove the abiguity from your question. – Frazell Thomas Commented Aug 22, 2011 at 22:00
- Do you mean "every second ma beginning with the first"? ("Every odd ma"?) You talk about pairs of mas yet in your example your string has an odd number of mas such that the one between 9 and 10 is not part of a pair yet you replace it anyway. Step one in solving a problem is understanding what the problem is... – nnnnnn Commented Aug 22, 2011 at 23:29
5 Answers
Reset to default 4var myNums = "1,2,3,4,5,6,7,8,9,10";
myNums.replace(/(.*?),(.*?,)?/g,"$1;$2");
That'll do it.
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"
You would do something like this:
myString.replace(/,/g, ';');
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 ma 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"
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(','), ';', ',');