How to use reverse() method In Javascript
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.
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));
Output
keeg
JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
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:
Contact Us