gene
gene

Reputation: 2108

How to convert string to Boolean in javascript?

I have a public property returned from my code-behind class to aspx page:

window.MyWIndow.IsFull = '<%=this.IsFull%>';

In code-behind it is defined this way:

public bool IsFull
{
    get;
    set;
}

Now, when I use it in my javascript file, I have the following code:

var isShow = myself.IsFull;

This way isShow is either 'True' or 'False'

I need to convert it on the page level, so isShow is boolean instead of string.

So I can write the if else logic

How can I do it?

Upvotes: 2

Views: 22123

Answers (4)

Brice
Brice

Reputation: 950

wrong answer is wrong...

A couple of options. You can use the built in Boolean object wrapper like this:

var string = myself.IsFull
var isShow = new Boolean(string.toLowercase);

or use the logical NOT operator twice like this:

var string = myself.IsFull
var isShow = !(!string.toLowercase);

edit: but why???? [![enter image description here][1]][1]

[1]: https://i.sstatic.net/359zg.png

Upvotes: -1

Jaromanda X
Jaromanda X

Reputation: 1

Alternative method is

window.MyWIndow.IsFull = <%=this.IsFull.ToString().ToLower()%>;

Note, no quotes

Upvotes: 0

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

You can use JSON.parse('true');

JSON.parse(isShow.toLowerCase());

Try the example below.

var result = ['True', 'False']

var isShow = result[Math.round(Math.random())];

console.log(JSON.parse(isShow.toLowerCase()));

Upvotes: 10

Shadow
Shadow

Reputation: 9427

If you know it's always going to return the string True and False, you could just use;

window.MyWindow.IsFull = '<%=this.IsFull%>' === "True";

Upvotes: 3

Related Questions