Determining string length in Node JS when string may be null - javascript

I'm trying to learn Node and have the function:
this.logMeIn = function(username,stream) {
if (username === null || username.length() < 1) {
stream.write("Invalid username, please try again:\n\r");
return false;
} else {
....etc
and I'm passing it
if (!client.loggedIn) {
if (client.logMeIn(String(data.match(/\S+/)),stream)) {
I've tried both == and ===, but I'm still getting errors as the username is not detecting that it is null, and username.length() fails on:
if (username === null || username.length() < 1) {
^
TypeError: Property 'length' of object null is not a function
I'm sure that Node won't evaluate the second part of the || in the if statement when the first part is true - but I fail to understand why the first part of the if statement is evaluating to false when username is a null object. Can someone help me understand what I've done wrong?

length is an attribute, not a function. Try username.length

You're passing String(data.match(/\S+/)) as username argument, so when data.match(/\S+/) is null, you get "null" not null for username, as:
String(null) === "null"
So you need to change your condition:
if( username === null || username === "null" || username.length < 1 )

If you require a non-empty string, you can do a simple "truthy" check that will work for null, undefined, '', etc:
if (username) { ... }
With that approach, you don't even need the .length check. Also, length is a property, not a method.
Edit: You have some funkiness going on. I think you need to start with how you're passing in your username - I don't think that your String(data.match(/\S+/)) logic is behaving the way that you're expecting it to (credit to #Engineer for spotting this).
Your match expression is going to return one or two types of values: null or an Array. In the case that it's null, as #Engineer pointed out, you end up passing in "null" as a string, which should resultantly pass your username check later on. You should consider revising this to:
if (!client.loggedIn) {
var matches = data.match(/\S+/);
if (client.logMeIn(matches ? matches[0] : '',stream)) {
Regarding .length being equal to 1 in all cases - that doesn't honestly make a lot of sense. I would recommend adding a lot of console.log() statements to try and figure out what's going on.

Try
if( username === null || username.toString().length < 1 )
I used if( username === null || username.length < 1 ) and it failed at length check.

Related

Way to test empty length property for null and return a string?

I am working through a challenge and trying to set it up so in the event that you pass a string you can determine if there are between 2 and 4 of the letter argument in that string.
My testing of the function worked, however if the matched array is 0 length (in the event there are no matching letters in said string) there is no way to measure the length. I get the error : TypeError: Cannot read property 'length' of null
I tried using a conditional that would return a string if the length was null. Didn't work, I'm not sure if there is a way to funnel this error into a conditional. Any ideas?
TLDR: Is there a way catch to TypeError: Cannot read property 'length' of null before it throws an error?
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex);
if (matched.length == null) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
countLetters('Letter', 'e');
true
countLetters('Letter', 'r');
false
countLetters('Letter', 'z');
//TypeError: Cannot read property 'length' of null
If(matched == null || matched.length != 0)
You can try let matched = string.match(regex) || [];
matched.length == null will always be false, so try matched.length === 0
two changes required to make it work as you need:
handle null when no match is found
check for length appropriately
corrected code below:
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex) || [];
if (matched.length == 0) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
i would strongly advise that you name your method appropriately. it isn't aligned with the return value or it's type. also, you return either string or a boolean value. one should refrain from that. return values of the same type irrespective of whether a match is found or otherwise.

Correctness of !args.value || args.value.length?

I'm reviewing this line of code. It has an expression that looks like this:
!args.value || args.value.length
For example suppose we do this:
let v = {};
console.log(!v.value); //logs true
console.log(v.value); //logs undefined
console.log(v.value.length); //Script wont run - cannot read property length of undefined
So even though value is undefined, we are proceeding to check that args.value.length (or undefined> is less than the constraint? So effectively we could be checking something like this ( IIUC ):
true throws
!undefined || undefined.length < 4
So I thought the purpose of the first check in the statement was to make sure that the undefined is actually defined?
So in other words it should be args.value && args.value.length? Or stated differently:
if args.value exists, then check the length of it?
Here's the entire snippet in context just for completeness:
if (isMinLength && (!args.value || args.value.length < args.constraints[0])) {
return eachPrefix + "$property must be longer than or equal to $constraint1 characters";
The < has higher precedence than ||:
if (isMinLength && (!args.value || (args.value.length < args.constraints[0]))) {
// ^ ^
So the condition matches if either args.value doesn't exist, or when its .length is too small.
At first its actually
!args.value || (args.value.length < args.constraints[0])
But you are right, the only difference to
args.value && args.value.length < args.constraints[0]
Is that the first always returns false while the second returns undefined if args.value is not defined. As you use that in an if statement, the outcome doesnt really matter.

null escaped in nodejs

I console.log("var = " + JSON.stringify(result.something));
I got var = null
but when I do
if(result.something !=null || result.something != ''){
console.log('enter')
}
it print enter also. I wonder why is that happening, I also tried result.something != 'null', it still go into the if statement.
Your variable is null, here's why:
1. (result.something !=null) : returns false
2. (result.something != '') : returns true
Since you've used an OR operator, program control is going to go inside the if block if either of the condition is true.
As your 2nd condition is evaluating to be true, it's going inside of the if block.
From javascript MDN:
null : "an empty value" i.e no object value present
null value is different from an empty string. So something like if(null ==== " ") will return false
your if statement always true because
the result.something is null AND it is not an empty string null != ''
:)

Javascript null or empty string does not work

I am trying to test that my string is null or empty, however it does not work.
My Code :
var veri = {
YeniMusteriEkleTextBox: $('#MyTextbox').val(),
};
if (veri.YeniMusteriEkleTextBox === "" ||
veri.YeniMusteriEkleTextBox == '' ||
veri.YeniMusteriEkleTextBox.length == 0 ||
veri.YeniMusteriEkleTextBox == null) {
alert("Customer Name can not be empty!!!");
}
How can ı check YeniMusteriEkleTextBox is null or empty ?
I would use the ! operator to test if it is empty, undefined etc.
if (!veri.YeniMusteriEkleTextBox) {
alert("Customer Name can not be empty!!!");
}
Also you do not need the comma after YeniMusteriEkleTextBox: $('#MyTextbox').val(),
Also testing for a length on an object that may be undefined will throw an error as the length will not be 0, it will instead be undefined.
You need to .trim the value to remove leading and trailing white space:
var veri = {
YeniMusteriEkleTextBox: $('#YeniMusteriAdiTextbox_I').val().trim()
};
The .trim method doesn't exist on some older browsers, there's a shim to add it at the above MDN link.
You can then just test !veri.YeniMusteriEkleTextBox or alternatively veri.YeniMusteriEkleTextBox.length === 0:
if (!veri.YeniMusteriEkleTextBox) {
alert("Customer Name can not be empty!!!");
}
You should use
if (!veri.YeniMusteriEkleTextBox) {
This also checks for undefined which is not the same as null
Since no one else is suggestion $.trim, I will
Note I removed the trailing comma too and use the ! not operator which will work for undefined, empty null and also 0, which is not a valid customer name anyway
var veri = {
YeniMusteriEkleTextBox: $.trim($('#MyTextbox').val())
};
if (!veri.YeniMusteriEkleTextBox) {
alert("Customer Name can not be empty!!!");
}

C# String.IsNullOrEmpty Javascript equivalent

I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.
For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)
What is the closest javascript (or jquery if then have one) call that would be equal?
You're overthinking. Null and empty string are both falsey values in JavaScript.
if(!theString) {
alert("the string is null or empty");
}
Falsey:
false
null
undefined
The empty string ''
The number 0
The number NaN
If, for whatever reason, you wanted to test only null and empty, you could do:
function isNullOrEmpty( s )
{
return ( s == null || s === "" );
}
Note: This will also catch undefined as #Raynos mentioned in the comments.
if (!string) {
// is emtpy
}
What is the best way to test for an empty string with jquery-out-of-the-box?
If you know that string is not numeric, this will work:
if (!string) {
.
.
.
You can create one Utility method which can be reused in many places such as:
function isNullOrEmpty(str){
var returnValue = false;
if ( !str
|| str == null
|| str === 'null'
|| str === ''
|| str === '{}'
|| str === 'undefined'
|| str.length === 0 ) {
returnValue = true;
}
return returnValue;
}
you can just do
if(!string)
{
//...
}
This will check string for undefined, null, and empty string.
To be clear, if(!theString){//...} where theString is an undeclared variable will throw an undefined error, not find it true. On the other hand if you have: if(!window.theString){//...} or var theString; if(!theString){//...} it will work as expected. In the case where a variable may not be declared (as opposed to being a property or simply not set), you need to use: if(typeof theString === 'undefined'){//...}
My preference is to create a prototype function that wraps it up for you.
Since the answer that is marked as correct contains a small error, here is my best try at coming up with a solution. I have two options, one that takes a string, the other takes a string or a number, since I assume many people are mixing strings and numbers in javascript.
Steps:
-If the object is null it is a null or empty string.
-If the type is not string (or number) it's string value is null or empty. NOTE: we might throw an exception here as well, depending on preferences.
-If the trimmed string value has a length that is small than 1 it is null or empty.
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
you can say it by logic
Let say you have a variable name a strVal, to check if is null or empty
if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null :)
}
else
{
//it is null or empty :(
}

Categories

Resources