Replicate String.prototype.trim
Your task is to implement a custom version of JavaScript's built-in String.prototype.trim() method. This method is fundamental for cleaning up strings by removing whitespace from both the beginning and end of a string. Mastering this will deepen your understanding of string manipulation and prototype extensions.
Problem Description
You need to create a JavaScript function named myTrim that behaves exactly like the native String.prototype.trim() method. This function should accept a string as its only argument and return a new string with all leading and trailing whitespace characters removed.
Key Requirements:
- The function should not modify the original string.
- Whitespace characters include space (' '), tab ('\t'), newline ('\n'), carriage return ('\r'), form feed ('\f'), and vertical tab ('\v').
- The function should correctly handle strings that are entirely whitespace, empty strings, or strings with no leading/trailing whitespace.
Expected Behavior:
- If a string has leading whitespace, it should be removed.
- If a string has trailing whitespace, it should be removed.
- If a string has both leading and trailing whitespace, both should be removed.
- If a string has no leading or trailing whitespace, it should be returned as is.
- If a string is empty, an empty string should be returned.
- If a string consists solely of whitespace characters, an empty string should be returned.
Examples
Example 1:
Input: " Hello World! "
Output: "Hello World!"
Explanation: Leading and trailing spaces are removed.
Example 2:
Input: "\t\n Some text with mixed whitespace \r\f\v"
Output: "Some text with mixed whitespace"
Explanation: All types of leading and trailing whitespace characters are removed.
Example 3:
Input: "No whitespace"
Output: "No whitespace"
Explanation: The string remains unchanged as there is no leading or trailing whitespace.
Example 4:
Input: ""
Output: ""
Explanation: An empty string input results in an empty string output.
Example 5:
Input: " "
Output: ""
Explanation: A string consisting only of whitespace characters results in an empty string.
Constraints
- The input will always be a string.
- The function should not use any regular expressions.
- The function should aim for reasonable performance and not be overly inefficient for typical string lengths.
Notes
Consider iterating through the string from both the beginning and the end. You'll need a way to identify all the characters that constitute whitespace. Think about how to handle the indices of the string to extract the relevant substring.