6

我正在寻找一个可以告诉我字符串可以转换为哪种数据类型的函数。例子:

"28.98" 产生浮点数(. 作为分隔符)

"44.332,95" 产生浮点数(,作为分隔符)

“29/04/14”导致日期(应该在国际范围内工作 -> 不同的日期格式)

"34.524" 产生 int (. 作为分隔符)

“所有其余的”结果为字符串

理想情况下也是(这些是字符串的子类):

“something@example.com” 生成电子邮件

“+49/2234/234567”导致电话

有没有(开源)库可以做这样的事情?

谢谢!

4

2 回答 2

6

你有它。不是一个库,不健康的正则表达式数量,但它适用于您的示例。如果您需要匹配其他内容,请添加更多示例。在评论中接受批评或要求。

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";
    }
}
于 2013-05-27T15:34:58.697 回答
-2

Has been a while since I worked with JavaScript frameworks, but what you are working on is rather simple. You can do it yourself, by checking if the logical differences exist in your string, the way you are presenting them here. For example, you can use the indexOf() JavaScript function to check if an @ sign exists in your string. If you have both a dot and a comma, means that you get a floating point number. Lastly, the difference you want between 28.98 and 34.524 cannot be presented in any way, since the . is always a floating point mark for numbers, meaning that 34.524 is a float for both human and computer.

Hope it helps - probably not with the library you were asking for though!

indexOf() function in w3schools.com

于 2013-05-27T14:58:19.833 回答