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
How to shift each letter in the given string N places down in the alphabet in JavaScript?
In the given problem statement our aim is to shift every letter in the given string N places down in the alphabet with the help of JavaScript functionalities. This is also known as the Caesar cipher technique.
Understanding the Problem
The problem at hand is to shift each character of the given string N places down in the alphabet using JavaScript. We need to take a string as input and update it by shifting every letter N positions down in the alphabet. For example, if the letter 'A' is shifted by 2 places down, it becomes 'C'. If 'Y' is shifted 2 places down, it wraps around and becomes 'A'.
Logic for the Given Problem
To solve this problem we will create a function which accepts two parameters: the string and the number of places to shift. We'll define the alphabet as a string containing all lowercase letters and use regular expressions to match all letters in the input string. For every matched letter, we'll convert it to lowercase, find its current index in the alphabet, calculate the new index by adding N (using modulo operator for wrapping), and return the shifted character while preserving the original case.
Algorithm
Step 1: Create a function shiftString() that accepts two parameters: string str and number N.
Step 2: Declare a string containing all alphabets for index reference.
Step 3: Use regular expressions to match all letters and process each one individually.
Step 4: Find the index of each letter in the alphabet string.
Step 5: Calculate the new position using (currentIndex + N) % 26 to handle wrapping.
Step 6: Preserve the original case of each letter in the result.
Step 7: Return the transformed string.
Example
// Function to shift the string n places down
function shiftString(str, N) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
const shiftedStr = str.replace(/[a-z]/gi, (match) => {
const lowercase = match.toLowerCase();
const currentIndex = alphabet.indexOf(lowercase);
const newIndex = (currentIndex + N) % 26; // Wrapping around the alphabet
const shiftedChar = alphabet[newIndex];
return (lowercase === match) ? shiftedChar : shiftedChar.toUpperCase();
});
return shiftedStr;
}
const inputString = 'Hello, Tutorials Point!';
const shiftedString = shiftString(inputString, 3);
console.log("Original:", inputString);
console.log("Shifted by 3:", shiftedString);
// Test with different shift values
console.log("Shifted by 13:", shiftString(inputString, 13));
console.log("Shifted by 26:", shiftString(inputString, 26)); // Full circle
Output
Original: Hello, Tutorials Point! Shifted by 3: Khoor, Wxwruldov Srlqw! Shifted by 13: Uryyb, Ghgbevnyf Cbvag! Shifted by 26: Hello, Tutorials Point!
Alternative Approach Using Character Codes
function shiftStringCharCode(str, N) {
return str.replace(/[a-z]/gi, (char) => {
const code = char.charCodeAt(0);
const base = code >= 65 && code <= 90 ? 65 : 97; // A=65, a=97
const shifted = ((code - base + N) % 26 + 26) % 26;
return String.fromCharCode(base + shifted);
});
}
const testString = "Hello World!";
console.log("Original:", testString);
console.log("Shifted by 5:", shiftStringCharCode(testString, 5));
Output
Original: Hello World! Shifted by 5: Mjqqt Btwqi!
Complexity Analysis
Time Complexity: O(n), where n is the length of the input string. The algorithm processes each character once.
Space Complexity: O(1) for the alphabet string approach, as it uses a fixed-size alphabet string of 26 characters regardless of input size.
Key Points
- The modulo operator (%) ensures proper wrapping around the alphabet
- Regular expressions efficiently match only alphabetic characters
- Case preservation maintains the original string format
- Non-alphabetic characters remain unchanged
Conclusion
The Caesar cipher implementation effectively shifts each letter N places down in the alphabet while preserving case and non-alphabetic characters. The solution has linear time complexity and handles edge cases like alphabet wrapping efficiently.
