I am looking for a function that can tell me to which data type a string might be converted. Examples:
"28.98" results in float (. as separator)
"44.332,95" results in float (, as separator)
"29/04/14" results in date (should work internationally -> different date formats)
"34.524" results in int (. as delimited)
"all the rest" results in string
Ideally also (these are subclasses of string):
"[email protected]" results in e-mail
"+49/2234/234567" results in phone
Is there a (open source) libary can can do such thing?
Thanks!
Edit: The current way to do it is typeof value === 'string' . For example: const str = 'hello'; if (typeof str === 'string') { ... }
typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.
To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.
Typeof in JavaScript is an operator used for type checking and returns the data type of the operand passed to it. The operand can be any variable, function, or object whose type you want to find out using the typeof operator.
There you have it. Not a library, unhealthy amount of regular expressions, but it works with your examples. If you need other things to be matched, please add more examples. Open to critique or requirements in the comments.
function getType(str){
if (typeof str !== 'string') str = str.toString();
var nan = isNaN(Number(str));
var isfloat = /^\d*(\.|,)\d*$/;
var commaFloat = /^(\d{0,3}(,)?)+\.\d*$/;
var dotFloat = /^(\d{0,3}(\.)?)+,\d*$/;
var date = /^\d{0,4}(\.|\/)\d{0,4}(\.|\/)\d{0,4}$/;
var email = /^[A-za-z0-9._-]*@[A-za-z0-9_-]*\.[A-Za-z0-9.]*$/;
var phone = /^\+\d{2}\/\d{4}\/\d{6}$/g;
if (!nan){
if (parseFloat(str) === parseInt(str)) return "integer";
else return "float";
}
else if (isfloat.test(str) || commaFloat.test(str) || dotFloat.test(str)) return "float";
else if (date.test(str)) return "date";
else {
if (email.test(str)) return "e-mail";
else if (phone.test(str)) return "phone";
else return "string";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With