String to Number Conversion in JavaScript
This challenge focuses on reliably converting strings to numbers in JavaScript. JavaScript's type coercion can be unpredictable, and this exercise aims to create a robust function that handles various input scenarios and returns a predictable numerical result. This is a common task in data processing and user input handling.
Problem Description
You are tasked with creating a JavaScript function called convertToNumber that takes a single argument, str, which is a string. The function should attempt to convert this string into a number. The function must handle various input types gracefully, including:
- Valid numerical strings (e.g., "123", "-45.67", "0")
- Strings with leading/trailing whitespace (e.g., " 123 ")
- Strings containing non-numeric characters that can be ignored (e.g., "123abc", "abc123") - only the numeric portion should be converted.
- Strings that cannot be converted to numbers (e.g., "abc", null, undefined, empty string "") - these should result in a return value of
NaN. - Boolean values (true/false) - these should be converted to 1 and 0 respectively.
The function should return a number. If the input string cannot be reasonably converted to a number, it should return NaN (Not a Number).
Examples
Example 1:
Input: "123"
Output: 123
Explanation: The input is a valid numerical string, so it's directly converted to the number 123.
Example 2:
Input: " -45.67 "
Output: -45.67
Explanation: The input string has leading and trailing whitespace, which is trimmed before conversion.
Example 3:
Input: "123abc"
Output: 123
Explanation: The input string contains non-numeric characters. Only the initial numeric portion ("123") is converted.
Example 4:
Input: "abc"
Output: NaN
Explanation: The input string does not contain any valid numeric characters, so the function returns NaN.
Example 5:
Input: ""
Output: NaN
Explanation: An empty string cannot be converted to a number.
Example 6:
Input: true
Output: 1
Explanation: Boolean true is converted to the number 1.
Example 7:
Input: false
Output: 0
Explanation: Boolean false is converted to the number 0.
Constraints
- The input
strwill always be a string, a number, a boolean, null, or undefined. - The function must handle all valid JavaScript number formats (integers, decimals, positive, negative).
- The function should be efficient and avoid unnecessary iterations or complex operations.
- The function should not throw errors.
Notes
Consider using regular expressions to extract the numeric portion of the string. Remember that JavaScript's Number() function and the unary plus operator (+) can be helpful, but be mindful of their behavior with invalid inputs. Think about how to handle edge cases like strings with only non-numeric characters or empty strings. Boolean values should be handled correctly.