JavaScript/格式转换

来自康健生活

引言

字符串转数组

"123456".replace(/(.)(?=[^$])/g, "$1,").split(",");
(6) ["1", "2", "3", "4", "5", "6"]

数组转字符串

["1", "2", "3", "4", "5", "6"].join('');
"123456"

数组字符串

JSON.stringify("123456".replace(/(.)(?=[^$])/g, "$1,").split(","));
"["1","2","3","4","5","6"]"

字符串转布尔

Boolean

let foo = 'true';
Boolean(foo);
true

eval

let foo = 'true';
eval(foo.toLowerCase());
true

===

let foo = 'true';
foo === 'true' ? true : foo === 'false' ? false : foo;
true

正则

let foo = 'true';
String.prototype.bool = function() { 
    return (/^true$/i).test(this); 
}; 
foo.bool();
true