// Remove last n occurrences of a substring
function removeLastNOccurrences(s, sub, n) {
const positions = [];
let pos = s.indexOf(sub);
// Find all occurrences
while (pos !== -1) {
positions.push(pos);
pos = s.indexOf(sub, pos + sub.length);
}
// Remove from the end
for (let i = positions.length - 1; i >= 0 && n > 0; i--, n--) {
const start = positions[i];
s = s.slice(0, start) + s.slice(start + sub.length);
}
return s;
}
// Remove extra spaces (collapse multiple spaces, trim ends)
function removeExtraSpaces(s) {
return s.trim().split(/\s+/).join(" ");
}
const text = "abc xyz xyz abc xyzabcxyz abc";
const result = removeLastNOccurrences(text, "xyz", 3);
console.log(result);
const cleaned = removeExtraSpaces(result);
console.log(cleaned);
/*
run:
abc xyz abc abc abc
abc xyz abc abc abc
*/