[英]How can I tell if a javascript string is a number OR a date?
I have a value that may be a stringified date, or number.我有一个可能是字符串化日期或数字的值。 I'd like to handle each case differently.
我想以不同的方式处理每种情况。
Date values can be any valid date string that can be parsed by a date library, like dayjs.日期值可以是任何可以被日期库解析的有效日期字符串,比如 dayjs。 For example:
"10/10/2020"
, "10-20-2020"
...例如:“2020 年 10 月 10 日
"10/10/2020"
、 "10-20-2020"
……
Number values can be actual numbers, or numbers in the form of a string, so values like 5
, "5.3"
, "10"
...数字值可以是实际数字,也可以是字符串形式的数字,因此值如
5
、 "5.3"
、 "10"
...
For example ->例如 ->
const number = parseFloat(value);
if (!isNaN(number)) {
return NumberValueConverter.prototype.toView(number);
}
const date = dayjs(value);
if (date.isValid()) {
return DateValueConverter.prototype.toView(value);
}
This code isn't working though - since date strings like 10-10-2020, 10-10-2020 end up getting parsed to 10
但此代码不起作用 - 因为像 10-10-2020、10-10-2020 这样的日期字符串最终会被解析为
10
If I do it in reverse, dayjs converts numbers like 10 to a valid date.如果我反过来做,dayjs 会将 10 之类的数字转换为有效日期。
parseFloat
is already happy when the given string starts with a digit, so if you then test isNaN
on that result, you'll get false positives.当给定的字符串以数字开头时,
parseFloat
已经很高兴了,所以如果你在那个结果上测试isNaN
,你会得到误报。
So don't check whether the result is numeric, but whether the original string represents a number:所以不要检查结果是否为数字,而是检查原始字符串是否代表数字:
if (!isNaN(number)) {
to:至:
if (!isNaN(value)) {
Alternatively, you can use the unary plus instead of parseFloat
, which will only return a definite number when the input represents a number:或者,您可以使用一元加号代替
parseFloat
,它只会在输入表示数字时返回一个确定的数字:
const number = +value;
... and then it is best practice to test with Number.isNaN
: ...然后最好使用
Number.isNaN
进行测试:
if (!Number.isNaN(number)) {
if(/^[0-9]+[.]{0,1}[0-9]*$/.test(value)) {
// Handle your number value
} else {
// Check for date here
}
You can use above regular expression for parsing number string.您可以使用上面的正则表达式来解析数字字符串。
You could use regex to test if the string looks like a date before mapping.您可以使用正则表达式来测试字符串是否看起来像映射前的日期。 This regex is from https://www.regextester.com/96683 And it tests if it looks like the date you passed in.
这个正则表达式来自https://www.regextester.com/96683它测试它是否看起来像你传入的日期。
There is more complex regex that tests for different formats of date if you do not know the format beforehand: https://stackoverflow.com/a/15504877/14948219如果您事先不知道格式,还有更复杂的正则表达式可以测试不同格式的日期: https://stackoverflow.com/a/15504877/14948219
if(([12]\d{3}/(0[1-9]|1[0-2])/(0[1-9]|[12]\d|3[01])).test(value)){
return date
} else if(isNan(value){
return number
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.