I want to replace some value in order
for example, below is a sample of xpath
/MCCI_IN200100UV01[@ITSVersion='XML_1.0'][@xsi:schemaLocation='urn:hl7-org:v3 MCCI_IN200100UV01.xsd']
/PORR_IN049016UV[r]/controlActProcess[@classCode='CACT']
[@moodCode='EVN']/subject[@typeCode='SUBJ'][1]/investigationEvent[@classCode='INVSTG']
[@moodCode='EVN']/outboundRelationship[@typeCode='SPRT'][relatedInvestigation/code[@code='2']
[@codeSystem='2.16.840.1.113883.3.989.2.1.1.22']][r]/relatedInvestigation[@classCode='INVSTG']
[@moodCode='EVN']/subjectOf2[@typeCode='SUBJ']/controlActEvent[@classCode='CACT']
[@moodCode='EVN']/author[@typeCode='AUT']/assignedEntity[@classCode='ASSIGNED']/assignedPerson[@classCode='PSN']
[@determinerCode='INSTANCE']/name/prefix[1]/@nullFlavor",
and, I would like to extract [r] in order and to replace from [0] to [n] depending on the number of elements.
how can I replace [r] ?
const txt = `/MCCI_IN200100UV01[@ITSVersion='XML_1.0'][@xsi:schemaLocation='urn:hl7-org:v3 MCCI_IN200100UV01.xsd']
/PORR_IN049016UV[r]/controlActProcess[@classCode='CACT']
[@moodCode='EVN']/subject[@typeCode='SUBJ'][1]/investigationEvent[@classCode='INVSTG']
[@moodCode='EVN']/outboundRelationship[@typeCode='SPRT'][relatedInvestigation/code[@code='2']
[@codeSystem='2.16.840.1.113883.3.989.2.1.1.22']][r]/relatedInvestigation[@classCode='INVSTG']
[@moodCode='EVN']/subjectOf2[@typeCode='SUBJ']/controlActEvent[@classCode='CACT']
[@moodCode='EVN']/author[@typeCode='AUT']/assignedEntity[@classCode='ASSIGNED']/assignedPerson[@classCode='PSN']
[@determinerCode='INSTANCE']/name/prefix[1]/@nullFlavor",`;
const count = (txt.match(/\[r\]/g) || []).length; // count occurrences using RegExp
let replacements; // set replacement values in-order
switch (count) {
case 0:
break
case 1:
replacements = ["a"];
break;
case 2:
replacements = ["___REPLACEMENT_1___", "___REPLACEMENT_2___"];
break;
case 3:
replacements = ["d", "e", "f"];
break;
}
let out = txt; // output variable
for (let i = 0; i < count; i++) {
out = out.replace("[r]", replacements[i], 1); // replace each occurrence one at a time
}
console.log(out);