See the commented code below:
function removeExtraHl7Fields(segmentToProcess, numberOfFieldsToKeep) {
// set the numberOfFieldsToKeep to a number for the for loop
numberOfFieldsToKeep = Number(numberOfFieldsToKeep);
// Get a count of the number of the segments to process in the message
var segmentCount = message.getCount(segmentToProcess);
//Loop through each segment that exists
for (var segment = 1; segment <= segmentCount; segment++) {
//Get the current segment so we have the data
var oldSegment = qie.parseHL7String(message.getNode(segmentToProcess, segment));
//set the segement in the mssage to blank so we can rebuild
message.setNode(segmentToProcess, segmentToProcess + '|', segment);
//Handle if this is an MSH segment
var field = 1;
if (StringUtils.equalsIgnoreCase(segmentToProcess, 'MSH')) {
field = 2;
}
//Loop through each field and put back the number of fields requested
for (field; field <= numberOfFieldsToKeep; field++) {
message.setNode(segmentToProcess + '-' + field, oldSegment.getNode(segmentToProcess + '-' + field), segment);
}
}
}
//Sample calls to the above function
removeExtraHl7Fields('MSH', 4);
removeExtraHl7Fields('PV1', '2');
removeExtraHl7Fields('PID', '8');