Creating a String
In this method, we maintain a string (or a character array) containing the English lowercase alphabet. Starting from the pivot point up to the length of the string, we retrieve the reversed alphabetical counterpart of a character by using its ASCII value as an index. By applying this approach, we convert the given string into the desired mirrored form.
Syntax:
let modifiedString = "";
for (let i = 0; i < startPosition; i++)
modifiedString = modifiedString + inputString[i];
for (let i = startPosition; i < inputStringLength; i++)
modifiedString = modifiedString + reverseAlphabet[inputString[i].charCodeAt() - 'a'.charCodeAt()];
Example: In the code we will implement above approach by creating a string.
function reverseAlphabetFromPosition(
inputString, startPosition) {
let reverseAlphabet =
"zyxwvutsrqponmlkjihgfedcba";
let inputStringLength =
inputString.length;
let newString = "";
for (let i = 0; i < startPosition; i++)
newString += inputString[i];
for (let i = startPosition; i < inputStringLength; i++)
newString += reverseAlphabet[inputString[i].
charCodeAt() - 'a'.charCodeAt()];
return newString;
}
let givenString = "w3wiki";
let startingPosition = 5;
console.log(
reverseAlphabetFromPosition(
givenString, startingPosition - 1));
Output
geekhulitvvph
Time Complexity: O(n)
Space Complexity: O(n)
JavaScript Program to Mirror Characters of a String
Our task is to mirror characters from the N-th position up to the end of a given string, where ‘a’ will be converted into ‘z’, ‘b’ into ‘y’, and so on. This JavaScript problem requires mirroring the characters in a string starting from a specified position. There are various approaches available to accomplish this, such as utilizing loops and maps. In this article, we will explore various methods to find the mirror characters of a string.
Examples:
Input : N = 3
paradox
Output : paizwlc
We mirror characters from position 3 to end.
Input : N = 6
pneumonia
Output : pnefnlmrz
Table of Content
- Method 1: Creating a String:
- Using a for loop
- Using Custom Mapping
- Using Array.reduce() Method
- Using Array.map() Method