Last active
August 8, 2021 16:22
-
-
Save thewhodidthis/3a2bd5b1a08030311660338db5d32ca4 to your computer and use it in GitHub Desktop.
Numerical string to number convert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "1.2" -> 1.2 | |
console.assert(convert('1.2') === 1.2) | |
// " " -> " " (not a number) | |
console.assert(isNaN(convert(' '))) | |
console.assert(isNaN(convert(''))) | |
// "12a" -> "12a" (not a number) | |
console.assert(convert('12a') === '12a') | |
console.assert(isNaN(convert('12a'))) | |
// null -> null (not a number) | |
console.assert(convert(null) === null) | |
// false -> false (not a number) | |
console.assert(convert(false) === false) | |
function convert(value) { | |
if (typeof value === 'string') { | |
// Parse doubly escaped line feeds | |
value = value.replace(/(\\n)/g, '\n') | |
// Typecast numerical looking values | |
value = isNaN(value) ? value : Number.parseFloat(value) | |
} | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment