JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
Last Updated :
09 Jul, 2024
In this article, we have given a string and the task is to write a javascript program to reverse only the consonants of a string without affecting the other elements’ positions and printing the output in the console.
Examples:
Input: hello
Output: lelho
Explanation: h,l,l are consonants in the given string.
After modifying the string their occurrences are l,l,h and
vowels positions are not changed.
These are the following approaches by using these we can solve the given question:
Using loop:
In this approach, we reverse the consonants in a given string. It initializes pointers at the start and end of the string, identifies consonants using a set, and swaps them until the pointers meet. If a character is not a consonant, the corresponding pointer is incremented or decremented accordingly. The code converts the array of characters back to a string and returns the modified string.
Example: This example shows the use of the above-explained approach.
JavaScript
// Function to reverse the
// consonants of the given string
function reverseConsonants(s) {
// Convert string to array of characters
let sArray = s.split('');
// Initialize pointers
let left = 0;
let right = s.length - 1;
// Define set of consonants
let consonants = new Set(['b', 'c', 'd', 'f', 'g',
'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's',
't', 'v', 'w', 'x', 'y', 'z']);
// While pointers don't meet
while (left < right) {
if (consonants.has(sArray[left].toLowerCase())
&& consonants.has(sArray[right].toLowerCase())) {
// Swap consonants
let temp = sArray[left];
sArray[left] = sArray[right];
sArray[right] = temp;
left++;
right--;
} else if (!consonants.has(sArray[left].toLowerCase())) {
left++;
} else if (!consonants.has(sArray[right].toLowerCase())) {
right--;
}
}
// Convert array back to string and return
return sArray.join('');
}
// Driver Code
let s = 'geek';
console.log(reverseConsonants(s));
Using reverse() method:
In this approach, the function generates a consonant list from the input string using array operations. It reverses this list, initializes an empty string, and iterates through the input, replacing consonants with reversed ones. It utilizes the 'match()' method for character checks, array methods like 'filter()' and 'reverse()', and string concatenation to build the modified string, which is then returned.
Example: This example shows the use of the above-explained approach.
JavaScript
function reverseConsonants(inputString) {
// Generate a list of consonants
// from the input string
let consonants = Array.from(inputString).
filter(char =>
char.match(/[a-zA-Z]/) && !'aeiouAEIOU'.includes(char));
// Reverse the list of consonants
consonants.reverse();
// Initialize a string variable
// to store the modified string
let outputString = '';
// Iterate through the input string and replace
// consonants with reversed consonants
for (let char of inputString) {
if (char.match(/[a-zA-Z]/) && !'aeiouAEIOU'.includes(char)) {
outputString += consonants.shift();
} else {
outputString += char;
}
}
// Return the modified string
return outputString;
}
let inputString = "geek";
console.log(reverseConsonants(inputString));
Using Two-Pointer Technique
Using the two-pointer technique to reverse consonants involves placing pointers at the beginning and end of the string, swapping consonants when both pointers are at consonants, and moving pointers inward. This continues until the pointers cross, ensuring non-consonants remain unaffected.
Example: In this example The function reverseConsonants reverses consonants in a string using a two-pointer technique, leaving other characters unchanged. It correctly reverses consonants while preserving the string's structure.
JavaScript
function reverseConsonants(str) {
const isConsonant = (char) => /[bcdfghjklmnpqrstvwxyz]/i.test(char);
let arr = str.split('');
let left = 0;
let right = arr.length - 1;
while (left < right) {
if (!isConsonant(arr[left])) {
left++;
} else if (!isConsonant(arr[right])) {
right--;
} else {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
return arr.join('');
}
console.log(reverseConsonants("Hello, World!")); // "Hollo, Werld!"
Using Regular Expressions and Array Manipulation:
This approach utilizes regular expressions to match consonants and then employs array manipulation techniques to reverse only the consonants while keeping the vowels and other characters in their original positions.
Example:
This approach provides another way to achieve the desired outcome by leveraging regular expressions and array manipulation techniques.
JavaScript
function reverseConsonantsWithRegex(str) {
// Define regular expression to match consonants
const consonantRegex = /[bcdfghjklmnpqrstvwxyz]/i;
// Convert the string to an array of characters
let arr = str.split('');
// Initialize pointers
let left = 0;
let right = arr.length - 1;
// Iterate through the array of characters
while (left < right) {
// Check if the character at the left pointer is a consonant
if (consonantRegex.test(arr[left])) {
// Check if the character at the right pointer is a consonant
if (consonantRegex.test(arr[right])) {
// Swap consonants
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
} else {
// Move the right pointer if the character at the right is not a consonant
right--;
}
} else {
// Move the left pointer if the character at the left is not a consonant
left++;
}
}
// Convert the array back to a string and return
return arr.join('');
}
// Test the function
console.log(reverseConsonantsWithRegex("Hello, World!")); // "Hollo, Werld!"
Using a Stack
This approach involves using a stack to store the consonants and then we replace the consonants in the original string with the ones popped from the stack.
Example:
In below example we use stack to Reverse Consonants in a Given String Without Affecting the Other Elements.
JavaScript
function isConsonant(char) {
return /^[bcdfghjklmnpqrstvwxyz]$/i.test(char);
}
function reverseConsonants(str) {
let arr = str.split('');
let stack = [];
// Push all consonants onto the stack
for (let char of arr) {
if (isConsonant(char)) {
stack.push(char);
}
}
// Replace consonants by popping from the stack
for (let i = 0; i < arr.length; i++) {
if (isConsonant(arr[i])) {
arr[i] = stack.pop();
}
}
return arr.join('');
}
// Example
const input = "geeksforgeeks";
const result = reverseConsonants(input);
console.log(result);
Approach: Using Recursion
In this approach, we use recursion to reverse only the consonants in a string. We will recursively process the string, swapping consonants at each recursive call until we have processed the entire string. This approach leverages the power of recursion to achieve the desired result in an elegant and efficient manner.
Example: This example demonstrates the use of the recursive approach to reverse only the consonants in a string.
JavaScript
function isConsonant(char) {
return /[bcdfghjklmnpqrstvwxyz]/i.test(char);
}
function reverseConsonantsHelper(strArray, left, right) {
if (left >= right) {
return strArray.join('');
}
if (!isConsonant(strArray[left])) {
return reverseConsonantsHelper(strArray, left + 1, right);
}
if (!isConsonant(strArray[right])) {
return reverseConsonantsHelper(strArray, left, right - 1);
}
// Swap consonants
[strArray[left], strArray[right]] = [strArray[right], strArray[left]];
return reverseConsonantsHelper(strArray, left + 1, right - 1);
}
function reverseConsonants(str) {
const strArray = str.split('');
return reverseConsonantsHelper(strArray, 0, strArray.length - 1);
}
// Test cases
console.log(reverseConsonants('hello')); // Output: 'lelho'
console.log(reverseConsonants('javascript')); // Output: 'tsirpvacaj'
console.log(reverseConsonants('example')); // Output: 'examlpe'
Outputlelho
taparcsivj
elapmxe
Similar Reads
JavaScript Program to Remove Vowels from a String The task is to write a JavaScript program that takes a string as input and returns the same string with all vowels removed. This means any occurrence of 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase) should be eliminated from the string. Given a string, remove the vowels from the string and
2 min read
JavaScript Program to Mirror Characters of a String Our task is to mirror characters from the N-th position up to the end of a given string, where 'a' will be converted into 'z', 'b' into 'y', and so on. This JavaScript problem requires mirroring the characters in a string starting from a specified position. There are various approaches available to
6 min read
Reverse Words Starting with Particular Characters using JavaScript We need to create a JavaScript function that reverses the order of all words in a given sentence that begins with a specific character. JavaScript allows us to reverse the words in a sentence that start with specific letters. Examples: Input: str= "I like to cook delicious meals every day"Character
4 min read
JavaScript Program to find Lexicographically next String In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order.Examples: Input : testOutput : tesuExplanation : The last character 't' is changed to
3 min read
Javascript Program To Reverse Words In A Given String Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"Examples:Â Input: s = "geeks quiz practice code"Â Output: s = "code practice quiz geeks"Input: s = "getting good at coding needs a lot of practice"Â Output: s = "pra
4 min read
Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = âabcdâOutput: 2Explanation:String after the left shift: âbcdaâString after the right shift: âdabc
3 min read
Javascript Program to Modify a string by performing given shift operations Given a string S containing lowercase English alphabets, and a matrix shift[][] consisting of pairs of the form{direction, amount}, where the direction can be 0 (for left shift) or 1 (for right shift) and the amount is the number of indices by which the string S is required to be shifted. The task i
3 min read
Print reverse string after removing vowels Given a string s, print reverse of string and remove the characters from the reversed string where there are vowels in the original string. Examples: Input : geeksforgeeksOutput : segrfsegExplanation :Reversed string is skeegrofskeeg, removing characters from indexes 1, 2, 6, 9 & 10 (0 based ind
13 min read
Reverse vowels in a given string Given a string s, reverse only the vowels in s while keeping the other characters in their original positions.Examples:Input: "geeksforgeeks"Output: "geeksforgeeks"Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks".Input: "helloworld"Output: "hollowerld"Explan
9 min read
Java Program To Reverse Words In A Given String Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "p
4 min read