💡
【JavaScript】string -> booleanへの変換
1. 厳密等価演算子を使う
一番お手軽かもしれないです.
const str = 'true';
const bool = (str === 'true');
console.log(bool); // true ✅
const str2 = 'false';
const bool2 = (str2 === 'true');
console.log(bool2); // false ✅
大文字小文字を区別したくなければtoLowerCase()
を付ければいいです.
2. JSON.parse()を使う
こんな方法もあります. 個人的にはちょっとキモく感じる.
const str = 'true';
const bool = await JSON.parse(str.toLowerCase());
console.log(bool); // true ✅
const str2 = 'false';
const bool2 = await JSON.parse(str2.toLowerCase());
console.log(bool2); // false ✅
無効な値ぶちこまれるとエラー吐いちゃうので防ぎたい場合はtry-catchしないといけないです.
❌やっちゃだめ
等価演算子は空文字列以外true
になるのでアウト
const str = 'false';
const bool = (str == true);
console.log(bool); // true ❌
Booleanオブジェクトも同様.
const str = 'false';
console.log(Boolean(str)); // true ❌
Discussion