This is a fun little problem (finding and marking the duplicates, that is - you'll have to figure out the rest), so I gave it a whirl.
The way I'd do it is in two passes: first to count the number of occurrences of each matched string, and then a second pass to actually wrap the strings. While we're at it, let's make it a general function where you can pass in the match pattern and wrapping strings.
Both passes use input.replace()
, but the first pass uses it only for the side effect that it can call a function on each match. This function doesn't even bother returning anything, because the code discards whatever value input.replace()
returns.
The second pass does the actual replacements and returns the resulting string.
var testString =
'PMC.12547QD/25874QD/26548QD/13254QD/45412QD.T05\n' +
'PMC.12454QD/19457QD/00035QD/25874QD/17354QD.T05\n' +
'PMC.00025QD/15454QD.T02';
var output = wrapDuplicates( testString, /\d+QD/g, '{', '}' );
console.log( output );
function wrapDuplicates( input, pattern, open, close ) {
var counts = {};
input.replace( pattern, function( match ) {
counts[match] = ( counts[match] || 0 ) + 1;
});
return input.replace( pattern, function( match ) {
return counts[match] > 1 ? open + match + close : match;
});
}
This logs:
PMC.12547QD/{25874QD}/26548QD/13254QD/45412QD.T05
PMC.12454QD/19457QD/00035QD/{25874QD}/17354QD.T05
PMC.00025QD/15454QD.T02