
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 alphabets in a string using JavaScript
Problem
We are required to write a JavaScript function that takes in a string, str, which consists of alphabets and some special characters.
Our function should return a new string based on the input string where all characters that are not alphabets stay in the same place, and all letters reverse their positions.
For example, if the input to the function is
Input
const str = 'k_lmn_opq';
Output
const output = 'q_pon_mlk';
Example
const str = 'k_lmn_opq'; const reverseAlphabets = (str) => { const arr = str.split('') let left = 0 let right = arr.length - 1 const swap = (a, b) => { const temp = arr[a] arr[a] = arr[b] arr[b] = temp } const isLetter = (x = '') => /[a-zA-Z]/.test(x) while (left <= right) { while (!isLetter(arr[left])) { left += 1 if (left > right) { break } } while (!isLetter(arr[right])) { right -= 1 if (left > right) { break } } if (left > right) { break } swap(left, right) left += 1 right -= 1 } return arr.join('') }; console.log(reverseAlphabets(str));
Output
q_pon_mlk
- Related Questions & Answers
- Reversing a string using for loop in JavaScript
- Reversing vowels in a string JavaScript
- Reversing words within a string JavaScript
- Reversing words in a string in JavaScript
- Reversing words present in a string in JavaScript
- Sorting alphabets within a string in JavaScript
- Reversing consonants only from a string in JavaScript
- Reversing the even length words of a string in JavaScript
- Reversing the order of words of a string in JavaScript
- Converting a string to NATO phonetic alphabets in JavaScript
- Reversing a string while maintaining the position of spaces in JavaScript
- Reversing strings with a twist in JavaScript
- Check if a string contains only alphabets in Java using Regex
- Padding a string with random lowercase alphabets to fill length in JavaScript
- Check if a string contains only alphabets in Java using Lambda expression
Advertisements