How to use Regular Expressions and Array Manipulation In Javascript
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.
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!"
Output
delro, WollH!
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: