- Trending Categories
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
Replace alphabets with nth forward alphabet in JavaScript
We are required to write a JavaScript function that takes in an alphabet string and a number, say n. We should then return a new string in which all the characters are replaced by respective alphabets at position n alphabets next to them.
For example, if the string and the number are −
const str = 'abcd'; const n = 2;
Then the output should be −
const output = 'cdef';
Example
The code for this will be −
const str = 'abcd'; const n = 2; const replaceNth = (str, n) => { const alphabet = 'abcdefghijklmnopqrstuvwxyz'; let i, pos, res = ''; for(i = 0; i < str.length; i++){ pos = alphabet.indexOf(str[i]); res += alphabet[(pos + n) % alphabet.length]; }; return res; }; console.log(replaceNth(str, n));
Output
And the output in the console will be −
cdef
Advertisements