Reverse a String in JavaScript
String reversal is a fundamental operation in computer science with applications in various areas like text processing, data manipulation, and algorithm implementation. This challenge asks you to write a JavaScript function that takes a string as input and returns a new string with the characters in reversed order. Mastering this concept is a great stepping stone to understanding more complex string manipulation techniques.
Problem Description
You are tasked with creating a JavaScript function called reverseString that accepts a single string argument. The function should return a new string containing the characters of the input string in reverse order. The original string should not be modified.
Key Requirements:
- The function must accept a string as input.
- The function must return a new string with the characters reversed.
- The function should handle empty strings and strings with a single character correctly.
- The function should be case-sensitive (e.g., "Hello" reversed is "olleH").
- The function should preserve spaces and other non-alphanumeric characters.
Expected Behavior:
The function should iterate through the input string from the last character to the first, constructing a new string with the characters in that order.
Edge Cases to Consider:
- Empty string: ""
- String with a single character: "a"
- String with spaces: "hello world"
- String with special characters: "!@#$%^"
- String with mixed case: "HeLlO"
Examples
Example 1:
Input: "hello"
Output: "olleh"
Explanation: The characters of "hello" are reversed to produce "olleh".
Example 2:
Input: "world"
Output: "dlrow"
Explanation: The characters of "world" are reversed to produce "dlrow".
Example 3:
Input: ""
Output: ""
Explanation: An empty string remains an empty string when reversed.
Example 4:
Input: "a"
Output: "a"
Explanation: A single-character string remains unchanged when reversed.
Example 5:
Input: "hello world"
Output: "dlrow olleh"
Explanation: Spaces are preserved during the reversal process.
Constraints
- The input string will contain only characters (letters, numbers, spaces, and special characters).
- The length of the input string will be between 0 and 1000 characters, inclusive.
- The function should execute in O(n) time complexity, where n is the length of the input string. While other approaches might work, prioritize efficiency.
Notes
Consider using a loop or built-in JavaScript methods to achieve the string reversal. Think about how you can efficiently build the reversed string without modifying the original. There are multiple ways to solve this problem; focus on clarity, efficiency, and correctness.