How to replace consecutive characters with only one using RegEx in Node.js

1 Answer

0 votes
function removeConsecutiveDuplicates(input) {
    // Matches any character (.) followed by itself one or more times (\1+)
    let pattern = /(.)\1+/g;

    // Replaces with the first captured group
    let result = input.replace(pattern, "$1");

    return result;
}

const input = "aaaaabbbbdccdddddddeeeeeeeeeee";
const modified = removeConsecutiveDuplicates(input);

console.log("Original:", input);
console.log("Modified:", modified);



/*
run:

Original: aaaaabbbbdccdddddddeeeeeeeeeee
Modified: abdcde

*/

 



answered Jun 7 by avibootz
...