How to use Iterative Loop In Javascript
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.
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
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