var st1 = "8,12,17,20";
var st2 = "8,12";
console.log(st1 ); //expected output (8-12, 17-20)
console.log(st2); // expected output (8-12);
I want to replace all alternative commas (of index position 1,3,5,7...) with hyphens using regex as shown in the example above. Thanks in advance.
CodePudding user response:
We can try the following approach:
var inputs = ["8,12,17,20", "8,12", "8,12,17"];
var outputs = inputs.map(x => x.replace(/(\d ),(\d )/g, "$1-$2"));
console.log(outputs);
The logic is simply to find each pair of numbers, from the start, and replace the comma with a hyphen. By definition, this will spare the even numbered commas in between number pairs.
A demo for earlier versions of JavaScript:
var inputs = ["8,12,17,20", "8,12", "8,12,17"];
for (var i=0; i < inputs.length; i) {
var output = inputs[i].replace(/(\d ),(\d )/g, "$1-$2");
console.log(inputs[i] " => " output);
}
CodePudding user response:
You can replace matches of the following regular expression with a hyphen:
,(?=(?:(?:\d ,){2})*\d $)
This matches commas that are followed later in the string by an even number of commas.
This expression can be broken down as follows.
, # match comma
(?= # begin a positive lookahead
(?: # begin a non-capture group
(?: # begin a non-capture group
\d , # match one or more digits followed by a comma
){2} # end non-capture group and execute it twice
)* # end non-capture group and execute it zero or more times
\d # match one or more digits
$ # match end of string
) # end positive lookahead
CodePudding user response:
var st1 = "8,12,17,20,3,4,5,6";
var st2 = "8,12";
//string to array
var array1=st1.split("");
var listIndex=[];
var z=0;
//Find all the comma from the array
function FindComnmaIndexlist(array1){
for(let i=0;i<=array1.length;i ){
if(array1[i]==','){
listIndex[z ]=i;
array1[i]='-';
}
}
}
// replace function
String.prototype.replaceAt = function(index, replacement) {
if (index >= this.length) {
return this.valueOf();
}
return this.substring(0, index) replacement this.substring(index 1);
}
// call find command index
FindComnmaIndexlist(array1);
// replace the comma
var nwts=st1;
for(let i=0;i<listIndex.length;i ){
let v=listIndex[i];
if(i%2==0){
nwts=nwts.replaceAt(v,'-');
}
}
//print
console.log(nwts);