converting string into Boolean value using JavaScript always give false - javascript

I am using the code below in JavaScript to change a string on the site to a Boolean value using JavaScript. when I alert test its says its true, but when I alter name bool is see flase any ideas why this would be the case.
var test = document.getElementById("name").value;
var nameBool= (String == test);

Compare the string to the value that you expect it to have when it should represent a true value:
var nameBool = test === "true";

I would guess that test is the boolean value of a checkbox? Then you would get a textual representation of it either by
var nameBool = String(test); // type conversion
or simpler
var nameBool = "" + test; // concatenation with empty string - implicit conversion
which then becomes "false" or "true", just as in your alert() (which did a stringification as well)
For the opposite, you'd use
var test = "true" // or "false"
var nameBool = test === "true" || (test === "false" ? false : throw new SyntaxError("non-boolean string value"));

Related

How to test if a string is a not number

I'm trying to verify if a string is text or number.
Could not find a proper way to verify.
Could you please advice?
Here is my problem:
var myNumber = "006";
var myText = "1. This is not a number";
isNaN(myNumber); // false
isNaN(myText); // false
I tried also:
isNaN(myNumber.split('.')[1]); // true
isNaN(myText.split('.')[1]); // true
parseInt(myNumber); // 6
parseInt(myText); // 1
What I would like to achieve would be to find when a string can be converted to a number (see myNumber). In case that the string is actually a text, how to spot it with javascript?
Could you please advise?
If I understood your question correctly I may have a solution but this will work even if the string is a number so here you go:
var yourNumber="55";
if(yourNumber*1==yourNumber){
alert("It's a number");
}else{alert("it's not a number");}
If parseInt() is not working for your desired results, you can try Number constructor. It gives you NaN for non-numbers, which you can verify by using isNaN() function.
var myNumber = "006";
var myText = "1. This is not a number";
console.log( Number(myNumber) );
console.log( Number(myText) );
Or you can use regular expressions:
var myNumber = "006";
var myText = "1. This is not a number";
var numRegex = /^\d+$/;
console.log( numRegex.test(myNumber) );
console.log( numRegex.test(myText) );
You can use regex.
function isNumber(num){
return /^(\d+)?(\.)?\d+$/.test(num);
}
isNumber("006") // true
isNumber(".6") // true
isNumber("1 not a number") // false
isNumber("23.63") // true
isNumber("23.6.3") // false
You can check if text is a number using isNaN function:
var myNumber = "006";
var myText = "1. This is not a number";
console.log(myNumber + ': ' + !isNaN(myNumber));
console.log(myText + ': ' + !isNaN(myText));
var reg = new RegExp('^[0-9]*$');
var myNumber = "006";
var myText = "1. This is not a number";
reg.test(myNumber) //true
reg.test(myText) //false
The short story:
I would really use the typeof operator.
From isNaN() | JavaScript MDN:
The isNaN() function determines whether a value is Not-A-Number or not. ... you may alternatively want to use Number.isNaN(), as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.
Long story:
Tried the following in a node console.
A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.
isNaN(123) // false
isNaN(true) // false
isNaN("123") // false
isNaN({}) // true
isNaN(undefined) // true
In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.
Number.isNaN(undefined) // false
Number.isNaN({}) // false
Number.isNaN(true) // false
Number.isNaN(123) // false
Number.isNaN(NaN) // true
Number.isNaN(0/0) // true
The typeof operator returns a string indicating the type of the unevaluated operand.
typeof(123) // number
typeof("123") // string
typeof(true) // boolean
Generally, the isNaN is the right idea, but you should parse it first:
var myNumber = "006";
var myText = "1. This is not a number";
Number.isNaN(Number.parseInt(myNumber)); // false
Number.isNaN(Number.parseInt(myText)); // true

RegEx how to use correctly to check str

Trying to use RegEx but doesn't work...what i've missed?How to alert message when it is "/0" in my calculator?
function div(input)
{
var input = document.getElementById("t").value;
var is_div_by_zero = /\/[\s.0]+$/.test(input);
if (is_div_by_zero)
{
alert(" / to Zero");
}
}
No need to do this with a regex, check the number value instead. E.g.
if (!Number(document.getElementById("t").value)) {
alert("Division by zero")
}
This will cast the value as a number and, when casted to a boolean, check if it's truthy or not. E.g. the value '1' will be casted to 1 which is true whereas 0 is false and 'foo' is NaN which is false.

How do I compare string and boolean in Javascript?

I got the Json "false" from server. I respond as bool but it's Json so it's in browser type is String instead of bool.
So if I run (!data) whenever I want to check "false" == false then they not worked.
So how can I parse bool from String in JavaScript then?
"true" == true and "false" == false. Then the code (!data) can check what it is [true and false]
If one of the operands is a boolean, convert the boolean operand to 1 if it is true and +0 if it is false.
When comparing a number to a string, try to convert the string to a numeric value.
from MDN Equality Operators page
Examples:
true == "true"; // 1 == NaN → false
true == "1"; // 1 == 1 → true
false == "false"; // 0 == NaN → false
false == ""; // 0 == 0 → true
false == "0"; // 0 == 0 → true
I would just explicitly check for the string "true".
let data = value === "true";
Otherwise you could use JSON.parse() to convert it to a native JavaScript value, but it's a lot of overhead if you know it's only the strings "true" or "false" you will receive.
var data = true;
data === "true" //false
String(data) === "true" //true
This works fine.
Try expression data == "true"
Tests:
data = "false" -- value will be false
date = "true" -- value will be true
Also, fix your JSON. JSON can handle booleans just fine.
If its just a json "false"/"true", you can use,
if(! eval(data)){
// Case when false
}
It would be more cleaner, if you restrict the code to accept only JSON data from server, and always jsonParse or eval it to JS object (something like jquery getJSON does. It accepts only JSON responses and parse it to object before passing to callback function).
That way you'll not only get boolean as boolean-from-server, but it will retain all other datatypes as well, and you can then go for routine expressions statements rather than special ones.
Happy Coding.
I think you need to look at how the JSON data is being generated. You can definitely have a normal JS boolean false in JSON.
{ "value1" : false, "value2" : true }
String.prototype.revalue= function(){
if(/^(true|false|null|undefined|NaN)$/i.test(this)) return eval(this);
if(parseFloat(this)+''== this) return parseFloat(this);
return this;
}
From: http://www.webdeveloper.com/forum/showthread.php?t=147389
Actually, you just need the first "if" statement from the function -- tests to find true or false in the code and the evals it, turning it into the boolean value
if(data+''=='true'){
alert('true');
}
Convert boolean to string by appending with blank string. and then compare with Stringobject.

javascript : checking boolean values

I have a boolean value set as a hidden variable in the form and I have the below javascript .
$().ready(function() {
var flag = $('#popUpFlag').val();
alert("flag = "+flag);
if(flag){
alert("flag is true");
}else{
alert("flag is false");
}
})
These are the outputs for the alert .
flag =
flag is false
flag = false
flag is false
flag = true
flag is false
My concern is obviously the third output . When the flag is true , why is it printing "flag is false" , instead of "flag is true" . I tested it in IE8 and FF 4
Suggestions are welcome.
No, you don't have a boolean value in the hidden field. The value in the field is always a string.
When you use the string value as if it was a boolean value, you get unexpected results. A condition is false if the value is false, 0, "" or null, but the string "false" is neither, so it's evaluated as true.
If you want a boolean value, you have to parse the string. An easy way is to simply check if the string has a specific value:
var flag = $('#popUpFlag').val() === 'true';
flag is a string, so have this instead:
if (flag === "true") {
//true
}
else if (flag === "false") {
//false
}
Hmm... I suspect that the value you are using is a string, so you're seeing the value correctly in the alert, but not when it tries to look at it like a boolean.
How can I convert a string to boolean in JavaScript?
Just try ocnverting to boolean and see if it still gives you the same issue

Javascript, String: Getting a Javascript var as a string

Because using .toString() for null vars doesn't work, and I can't be checking each and every one of these in my particular application.
I know this is a stupidly simple problem with an answer that literally must be staring me in the face right now.
The non-concatenation route is to use the String() constructor:
var str = new String(myVar); // returns string object
var str = String(myVar); // returns string value
Of course, var str = "" + myVar; is shorter and easier. Be aware that all the methods here will transform a variable with a value of null into "null". If you want to get around that, you can use || to set a default when a variable's value is "falsey" like null:
var str = myVar || "";
Just so long as you know that 0 and false would also result in "" here.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String
How about
var str = '' + someVar;
What about
var str = (variable || "");
//or
(variable || "").toString();
Of course you'll get this for false, undefined and so on, too, but it will be an empty string and not "null"
String(null) returns "null", which may cause problems if a form field's value is itself null. How about a simple wrapper function instead?
function toString(v) {
if(v == null || v == undefined) {
return "";
}
return String(v);
}
Only null, undefined, and empty strings should return the empty string. All other falsy values including the integer 0 will return something else. Some tests,
> toString(null)
""
> toString(undefined)
""
> toString(false)
"false"
> toString(0)
"0"
> toString(NaN)
"NaN"
> toString("")
""
How about ... ?
var theVarAsString = "" + oldVar;

Categories