Open In App

JavaScript Program to Remove Consecutive Duplicate Characters From a String

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to implement a JavaScript program to remove consecutive duplicate characters from a string. In this program, we will eliminate all the consecutive occurrences of the same character from a string.

Example:

Input: string: "geeks" 
Output: "geks"
Explanation :consecutive "e" should be removed

Using Iterative Loop

In this approach, we are using the for loop and if else statement to check if the current letter is the same as the last character or not. If it is, then we are skipping it, and if not, we are adding that character to the output string.

Syntax:

for (const letter of inputData) {
if (letter !== lastChar) {
output += letter;
lastChar = letter;
}
}

Example: This example shows the use of the above-explained approach.

Javascript




const eleminateSameConsecutiveCharacters =
    (inputData) => {
        let output = "";
        let lastChar = "";
  
        for (const letter of inputData) {
            if (letter !== lastChar) {
                output += letter;
                lastChar = letter;
            }
        }
  
        return output;
    };
  
const testString = "Geeks For Geeks";
console.log(
    eleminateSameConsecutiveCharacters(
        testString
    )
);


Output

Geks For Geks

Using Regular Expressions

In this approach, we are traversing each character of the string and checking if it is the same as the last character or not using the replace method. If it is the same, then we skip it; otherwise, we return it.

Syntax:

inputData.replace(/(.)\1+/g, '$1');

Example: This example shows the use of the above-explained approach.

Javascript




const eleminateSameConsecutiveCharacters =
    (inputData) => {
        return inputData.replace(
            /(.)\1+/g,
            "$1"
        );
    };
  
const testString = "Geeks For Geeks";
console.log(
    eleminateSameConsecutiveCharacters(
        testString
    )
);


Output

Geks For Geks


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads