将字符串解析为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) '' -> nullAre 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.
更多推荐
发布评论