How to use a for loop In Javascript
- Initialize an empty string to store the mirrored result.
- Iterate through the characters of the given string using a loop.
- When the loop index is equal to or greater than the starting position, replace the current character with its mirror (e.g., ‘a’ becomes ‘z’ and ‘b’ becomes ‘y’).
- Append the mirrored character to the result string.
Syntax:
for (let i = 0; i < givenString.length; i++) {
// condition
}
Example: In the code we will implement above approach by using single for loop.
let givenString = "w3wiki";
let startingPosition = 5;
let mirroredString = '';
for (let i = 0; i < givenString.length; i++) {
if (i >= startingPosition - 1) {
mirroredString +=
String.fromCharCode(219 - givenString.charCodeAt(i));
} else {
mirroredString += givenString[i];
}
}
console.log(mirroredString);
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