Skip to content

Instantly share code, notes, and snippets.

@thewhodidthis
Last active August 8, 2021 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thewhodidthis/3a2bd5b1a08030311660338db5d32ca4 to your computer and use it in GitHub Desktop.
Save thewhodidthis/3a2bd5b1a08030311660338db5d32ca4 to your computer and use it in GitHub Desktop.
Numerical string to number convert
// "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