JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
Last Updated :
07 Nov, 2023
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 reverseConsonants(s) {
let sArray = s.split( '' );
let left = 0;
let right = s.length - 1;
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 (left < right) {
if (consonants.has(sArray[left].toLowerCase())
&& consonants.has(sArray[right].toLowerCase())) {
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--;
}
}
return sArray.join(' ');
}
// Driver Code
let s = ' geek';
console.log(reverseConsonants(s));
|
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) {
let consonants = Array.from(inputString).
filter(char =>
char.match(/[a-zA-Z]/) && ! 'aeiouAEIOU' .includes(char));
consonants.reverse();
let outputString = '' ;
for (let char of inputString) {
if (char.match(/[a-zA-Z]/) && ! 'aeiouAEIOU' .includes(char)) {
outputString += consonants.shift();
} else {
outputString += char;
}
}
return outputString;
}
let inputString = "geek" ;
console.log(reverseConsonants(inputString));
|
Share your thoughts in the comments
Please Login to comment...