Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Moving every alphabet forward by 10 places in JavaScript
Problem
We need to write a JavaScript function that takes a string of English alphabets and shifts every letter forward by 10 positions. When a letter goes past 'z', it wraps around to start again at 'a'.
Example
Following is the code −
const str = 'sample string';
const moveStrBy = (num = 10) => {
return str => {
const calcStr = (ch, code) => String
.fromCharCode(code + (ch.charCodeAt(0) - code + num) % 26);
const ACode = 'A'.charCodeAt(0);
const aCode = 'a'.charCodeAt(0);
return str.replace(/[a-z]/gi, ch => (
ch.toLowerCase() == ch
? calcStr(ch, aCode)
: calcStr(ch, ACode)
));
};
};
const moveByTen = moveStrBy();
console.log(moveByTen(str));
Output
ckwzvo cdbsxq
How It Works
The solution uses a higher-order function approach:
-
moveStrBy()returns a function that shifts characters by the specified number -
calcStr()handles the character shifting with modulo arithmetic to wrap around -
replace()with regex/[a-z]/giprocesses all alphabetic characters - Preserves original case by checking if the character is lowercase or uppercase
Simplified Version
Here's a more direct approach for shifting by 10 positions:
function shiftAlphabetBy10(str) {
return str.replace(/[a-zA-Z]/g, char => {
const isLowerCase = char >= 'a' && char
Rovvy Gybvn
Key Points
- Uses
charCodeAt()to get ASCII values andString.fromCharCode()to convert back - Modulo operator (%) ensures wrapping from 'z' to 'a' or 'Z' to 'A'
- Preserves case and non-alphabetic characters remain unchanged
- The shift value of 10 moves 'a' to 'k', 'b' to 'l', etc.
Conclusion
This alphabet shifting technique uses ASCII arithmetic with modulo operations to create a Caesar cipher-like transformation. The approach efficiently handles case preservation and character wrapping.
Advertisements
