How to check if this a string
is considered a BigInt
I have the following possible numbers that are returned based on a RegEx
4
5
12
76561198036527204 // This is a string but want to cast to a bigint
a-string-value // A string can also be returned by the regex and should stay a string
true
The above numbers are all returned as strings, but I want to cast them based on their type, but don’t know how to validate if a string
is a BigInt
I looked up lodash
had a function like this but it doesn’t.
Simply checking for isSafeInteger
doesn’t work, because the RegEx
can also return other types besides numbers and bigints, like strings and booleans
So the expected output from above would be
4 // number
5 // number
12 // number
76561198036527204 // bigint
a-string-value // string
true // bool
2
Answers
‘When tested against typeof, a BigInt value (bigint primitive) will give "bigint"’
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
Check if the parsed value matches the original value –
Technically that would also say that it’s a valid number, so if you also checked if it was a number (lots of similar questions for that) and then discounted those first etc