0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】文字列をブール値に変換する方法

Posted at

===を使用する

===で文字列がtrueか判定します。大文字と小文字が区別されるため、toLowerCase()が必要な場合があります。

const boolString = "True"
const boolValue = (boolString.toLowerCase() === "true")
console.log(boolValue) // true

正規表現を使用する

以下のように正規表現を使用して文字列がtrueか判定します。

const boolString = "true"
const boolValue = (/true/).test(boolString)
console.log(boolValue) // true

大文字と小文字を区別しない場合には次のようにします。

const boolString = "True"
const boolValue = (/true/i).test(boolString)
console.log(boolValue) // true

!!を使用する

この方法は上記2つとは異なり、空文字か否かを判定します。

const stringValue1 = !!'true'
const stringValue2 = !!''

console.log(stringValue1) // true
console.log(stringValue2) // false

Boolean()を使用する

この方法も空文字か否かを判定します。

const stringValue1 = Boolean('true')
const stringValue2 = Boolean('')

console.log(stringValue1) // true
console.log(stringValue2) // false
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?