How to use Index Comparison In Javascript
In this approach, we utilize an iterative loop and compare characters using their indices to identify consecutive duplicate characters. We iterate through the string and compare each character with the next character. If they are different, we append the current character to the output string. This approach does not rely on an additional data structure.
Example:
function removeConsecutiveDuplicates(inputData) {
let output = "";
for (let i = 0; i < inputData.length; i++) {
// If current character is not the same as next character
if (inputData[i] !== inputData[i + 1]) {
output += inputData[i];
}
}
return output;
}
const testString = "Geeks For Geeks";
console.log(removeConsecutiveDuplicates(testString));
Output
Geks For Geks
JavaScript Program to Remove Consecutive Duplicate Characters From a String
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
Table of Content
- Using Iterative Loop
- Using Regular Expressions
- Using Array Methods
- Using Index Comparison