- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reversing consonants only from a string in JavaScript
Problem
We are required to write a JavaScript function that takes in a string of lowercase english alphabets as the only argument.
The function should construct a new string in which the order of consonants is reversed and the vowels hold their relative positions.
For example, if the input to the function is −
const str = 'somestring';
Then the output should be −
const output = 'gomenrtiss';
Example
The code for this will be −
const str = 'somestring'; const reverseConsonants = (str = '') => { const arr = str.split(""); let i = 0, j = arr.length - 1; const consonants = 'bcdfghjklnpqrstvwxyz'; while(i < j){ while(i < j && consonants.indexOf(arr[i]) < 0) { i++; } while(i< j && consonants.indexOf(arr[j]) < 0) { j--; } let tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } let result = ""; for(let i = 0; i < arr.length; i++) { result += arr[i]; } return result; }; console.log(reverseConsonants(str));
Output
And the output in the console will be −
gomenrtiss
Advertisements