将字符串解析为bool,float,number,date或string(Parse string into bool, float, number, date or string)

编程入门 行业动态 更新时间:2024-10-09 11:16:43
字符串解析为bool,float,number,date或string(Parse string into bool, float, number, date or string)

假设我已经控制了输入,我可以创建一个函数,将字符串转换为基于“最佳猜测”的正确类型。

'2017-12-24' -> string '2017-12-24' (implement with a simple regex) '2017' -> number 2017 (implement with parseInt - ok to ignore any letters that follows) '201.7' -> float 201.7 (implement with parseFloat - ok to ignore any letters that follows) 'True' -> bool true (implement with [].indexOf - TRUE, False, false, true also) 'foo' -> string 'foo' (implement withreqex - anything starting with a letter) '' -> null

是否有任何lib已经这样做了?

Assume that I have control of the inputs, I can create a functions that converts a string to correct type based on "best guesses".

'2017-12-24' -> string '2017-12-24' (implement with a simple regex) '2017' -> number 2017 (implement with parseInt - ok to ignore any letters that follows) '201.7' -> float 201.7 (implement with parseFloat - ok to ignore any letters that follows) 'True' -> bool true (implement with [].indexOf - TRUE, False, false, true also) 'foo' -> string 'foo' (implement withreqex - anything starting with a letter) '' -> null

Are there any libs that already does this?

最满意答案

向上转型

upcast是一个JS类型的检查/铸造库。 一些例子:

upcast.type([]); // 'array' upcast.is(123, 'string'); // false upcast.to('foo', 'array'); // ['f', 'o', 'o']

这个图书馆可能没有维护,但你会有想法写你自己的。

upcast

upcast is a JS type checking/casting library. Some examples:

upcast.type([]); // 'array' upcast.is(123, 'string'); // false upcast.to('foo', 'array'); // ['f', 'o', 'o']

This library may be unmaintained, but you'll get an idea to write your own.

更多推荐

本文发布于:2023-08-07 11:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464035.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   float   bool   number   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!