Compare string with GM_GetValue not working as excepted - javascript

I am trying to compare value of TestScript with string "Investisseur" But this seems not working and I don't go into the if statement.
console.log(GM_getValue(TestScript));
if(GM_getValue(TestScript) == "Investisseur")
{
//Should be there
}
console.log(GM_getValue(TestScript)); returns :
So the if condition would return true and not false .. What Am I doing Wrong ?
EDIT
It seems like the check before reset my #GM_getValue:
if(GM_getValue(TestScript) == "Investisseur" || GM_getValue(TestScript) == null || GM_getValue(TestScript) == undefined ){
GM_setValue(TimeoutMain, 1000)
}else if(GM_getValue(TestScript) == "Emetteur"){
GM_setValue(TimeoutMain, 10000)
}
Any Idea why ? When I try to Console.log after this it display nothing .. Why is the value deleted ?
Maybe more understandable with a screen there :

TestScript might have extra spaces.
trim() removes leading and trailing whitespace.
Try replacing:
GM_getValue(TestScript)
with:
if (GM_getValue(TestScript).trim() == "Investisseur")

Related

Why does this JavaScript validation work depending on the order of conditions?

I am writing one small function which validates one text, and I am very upset because of the validation.
The problem is: when I try to compare the string to null (to check the cancel button), it works depending on where I put the condition! It seems to be working only when I put at the beginning of the validation. I have tested it with parenthesis for each condition too, but I get the same result.
What´s happening here?
I found this answer on Stack Overflow, but it is for Python and I don´t understand it very well:
Does the Order of Conditions affect Performance?
Code
function validate()
{
var isValid = false;
var text;
while (isValid == false)
{
text = prompt("Enter one text between 1 and 10 characters, no empty, blank spaces, only numbers");
/*
WITH NULL (CANCEL BUTTON) VALIDATION AT THE BEGINNING,
IT WORKS:
*/
if (text != null &&
(text.length >= 1 && text.length <= 10) &&
text != "" &&
isNaN(text) == false)
{
isValid=true;
}
/*
WITH NULL (CANCEL BUTTON) VALIDATION AT ANOTHER POSITION, IT DOESN´T WORK:
It generates "TypeError:Text is null"
*/
if ( (text.length >= 1 && text.length < 10) &&
isNaN(text) == false && text != "" && text !=null)
{
isValid = true;
}
}
if (isValid == true)
{
// Some code when validation is OK
}
}
You want to check if the text is not null first, because if that condition fails, the rest of the conditions will not be evaluated, since the && invariant has been violated. If the text is null, and the null check comes after some other check, you will receive an error.
Because let's say that we had the following values:
var text = 'Tim is an alright person',
notText = null
If we try to access a property of notText, we will get an error because null doesn't have a properties like length. So, in code:
if(text.length){...}
works because text has a length property. However, the following does not work:
if(notText.length){...}
because notText does not have a length property. It will throw the error of TypeError because you are trying to do something with the null type that is not allowed.
So, we need the text != null check first because it will fail early, before trying the other expressions.
In simple words:
If you evaluate text.anyproperty == null you're asking if the anyproperty of the var text is null, but this way you are taking for granted that text is not null, which will fail with the error you mentioned (TypeError) if text is actually null.
In order to avoid this pitfall you must ask first for text and then for text.anyproperty like this: if(text != null && text.anyproperty != null) ... so, this way, if text != null fails, the text.anyproperty != null will not be evaluated and you won't get the TypeError.
For the purpose of your validation, using if(text != null && text.anyproperty != null) you can achieve your goal, since if text is null, it doesn't make any sense check text.anyproperty (that's why the rest of the expression, the code after &&, is not evaluated).
Hope this help you understand better this matter :)

Cannot check for an equal number using string

I have what I thought would be a simple logic check. In my code
$scope.seatMap.PlaneTypeCode = "175"
However, when I set
$scope.seatMap.PlaneTypeCode === "175" //my debugger returns <b>false </b>
parseInt($scope.seatMap.PlaneTypeCode,10) ===175 // equals 17
I added a few zeros on the radix but that did nothing to help.
I am not sure how to do a comparison check. Any insight on this would be hugely appreciated.
Here is my full if statement
if (parseInt(col.name,10) ===4 && parseInt($scope.seatMap.PlaneTypeCode,10) ===175 && $scope.TripSummary) {
col.available = false;
}
****** Changed my response to this
if (parseInt(col.name,10) ===4 && $scope.seatMap.PlaneTypeCode ==="175" && $scope.TripSummary) {
col.available = false;
} // still getting false
=== is a best practice, you should use it. Review the reference provided by #Joyson
You don't need the ,10 in parseInt because it is the default.
var PlaneTypeCode = "175";
if (parseInt(PlaneTypeCode) === 175) {
console.log('equal');
}
If PlaneTypeCode is a code and can contain anything other than digits, a better comparison would be:
if (PlaneTypeCode === "175")
You can use == instead of ===
$scope.seatMap.PlaneTypeCode == "175"
Please refer to Difference between == and === to know more
use angular.equals($scope.seatMap.PlaneTypeCode,"175")

Javascript disallow space only in input area

I tried using following method to ban users from leaving only space in the input area with no luck:
method one:
var formSub = $('#formsub').val();
if (formSub == null || formSub == "") {
return false;
}
method two:
if (formSub.trim() == "" || formSub.trim() == " ") {
return false;
}
method three:
if ($.trim(formSub) == "" || $.trim(formSub) == " ") {
return false;
}
Any thought? :)
Use a simple regexp:
/\S/.test(formSub)
where \S refers to any non-white space character.
This removes the dependency on trim (not found in IE<=8) and/or jQuery.
It should be formSub == null || formSub.trim() === "".
=== and == isn't exactly the same. == "" can means true, and any string is "true".
Try:
if (formValue.length === 0 || !formValue.trim()) {
return false;
}
Haha! This is a good one you actually walk around the solution all along.
So here for example, you actually already trimmed all the spaces by using .trim()
if (formSub.trim() == "" || formSub.trim() == " ") {
return false;
}
Correct would be just,
if (formSub == " ") {
return false;
}
This will be the most useful, it passes if someone actually wrote something different from spaces, or other invisible characters ;)
Google "Javascript Regex for more info"
if (/\S/.test(formSub)) {
// String is not empty
}
else{
// String is empty and not usefull
}
Cheers ;) ! +1 Appreciated

What does text != "" mean?

This is from chapter 6 in Eloquent Javascript:
Code:
function splitParagraph(text) {
var fragments = [];
while( text != "" ) // ?
if (text.charAt(0) == "*") {
fragments.push({type: "emphasized"});
etc...
I am having trouble grasping what the while loop is doing. Text is a string. Does the while loop read "while text doesn't have any characters remaining.." Is the while loop looking at every character in the string one by one making sure there is another character left?
The while loop keeps running while the condition inside is true. In this case, text != "" is true if the string in question is not an empty string.
In this particular case, I guess text must be changed somewhere inside the loop, otherwise it doesn't make sense to use a while construct here.
NOTE: Actually, in JavaScript, the != and == operators will evaluate in a pretty curious way: 0, [] and "", for instance, will all be considered equal:
"" != [] -> false
0 != [] -> false
0 != "" -> false
=== and !== can be used to enforce strict equality.
It checks if text isn't an empty string (length 0 and containing no characters).
"Is the while loop looking at every character in the string
one by one making sure there is another character left?"
Yes though the entire loop is not shown that is almost certainly what is being done.
The while condition checks if the text string is empty.
If not empty, the loop iterates through the body of the loop.
The text.charAt(0) checks the first character of the string. If a '*' character is found,
an element is added to the fragments array.
Within the body there will be code to remove the first character of the text string
and the loop then processes the next character of the string.
while( text != "" )
if (text.charAt(0) == "*") {
fragments.push({type: "emphasized"});
What does text != “” mean?
It means if the value of text can not be coerced to match ""
consider this code
if ("abc" != "") {
console.log("1 ok");
}
if ([] != "") {
console.log("2 ok");
}
if (0 != "") {
console.log("3 ok");
}
if (false != "") {
console.log("4 ok");
}
on jsfiddle
Oh dear, what happened in case 2 and 3 and 4?

Seemingly redundant ternary operators in javascript

The following is common code floating around online that checks if cookies are enabled in a particular browser:
var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
document.cookie = "testcookie"
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false
}
if (!cookieEnabled) {
// do some work
}
Why are the first and fifth lines ternary statements? Does
var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;
catch some case that the following wouldn't?
var cookieEnabled = (window.navigator.cookieEnabled);
The same goes for the fifth line.
The ternary statement at the first line is useful in that it coverts a possible non-boolean value into a boolean one. Consider the following code
window.navigator.cookieEnabled = "evil people do this";
The above is legal and as the value says evil people do do this. Without the ternary statement the following code wouldn't execute as expected
if (cookiesEnabled === false) {
// ...
}
To be precise:
(window.navigator.cookieEnabled) ? true : false
is equivalent to:
!!window.navigator.cookieEnabled
However:
(document.cookie.indexOf("testcookie") != -1) ? true : false
can be simply replaced by:
document.cookie.indexOf("testcookie") != -1
Finally:
cookieEnabled == false
can be changed to:
!cookieEnabled
So what's the problem with the first case? In JavaScript non-zero numbers, non-empty strings, etc. evaluate to true. So if(window.navigator.cookieEnabled) passes for cookieEnabled being equal to "foo" and 42 as well. If you really want to have a variebale of boolean type, you must negate it twice.

Categories