C# String.IsNullOrEmpty Javascript equivalent - javascript

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 :(
}

Related

Check if String can be converted to number

I created the following Typescript extension to convert a string to Number:
declare global {
interface String {
toNumber(): number | null;
}
}
String.prototype.toNumber = function(this: string) {
return parseFloat(this);
}
When it is not possible to parse the string to number either because it is invalid, null, undefined, etc I would always like to return null.
How can I do this?
I am assuming you already understand the differences between parseFloat / Number as conversion mechanisms.
Effectively all you need to do is check if the output is NaN. You can do this by:
String.prototype.toNumber = function(this: string) {
const num = parseFloat(this);
return Number.isNaN(num) ? null : num;
}
If you want to return either a non-zero valid number (well, note that NaN is a number, but I think I know what you mean), then check for what you don't want before returning:
Object.defineProperty(String.prototype, "toNumber", {
value: function(str) {
let num = Number(str);
return num === 0 || isNaN(num) ? null : num;
}
});
(Defining properties directly on the prototype is a bad habit and can lead to weird behavior; using .defineProperty gives you a property that is not enumerable.)
Oh, and that's JavaScript, obviously, not Typescript.
A simple answer would be to use return Number(this) || null;
The Number function will convert to a number or NaN, NaN || null will return null (because NaN is falsey).
Updated added testing for zero condition, which with the above code would have also returned null. If that is not what you want, this code will allow zero to return. (Note that this can be done many different ways!):
const parsedValue = Number(this);
return parsedValue === 0 ? parsedValue : parsedValue || null;
Updated to use the parseFloat function, example of early exit for string of '0'. Very similar to the previous updated example.
if (this === '0') {
return 0;
}
return parseFloat(this) || null;

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.

Typescript : check a string for number

I'm new to web development, and in my function want to check if a given string value is a number. In case the string isn't a valid number I want to return null.
The following works for all cases except when the string is "0" in which case it returns null.
parseInt(columnSortSettings[0]) || null;
How do I prevent this from happening. Apparantly parseInt doesn't consider 0 as an integer!
Since 0 is act as false , so you can use isNaN() in this case
var res = parseInt(columnSortSettings[0], 10);
return isNaN(res) ? null : res;
It's because you are basically testing 0 which is also false.
You can do
var n = columnSortSettings[0];
if(parseInt(n, 10) || n === '0'){
//...
}
You can also test instead if it's a number
if(typeof(parseInt(n, 10)) === 'number'){
//...
}
But beware cause
typeof Infinity === 'number';
typeof NaN === 'number';
You can use the isNumeric operator from rxjs library (importing rxjs/util/isNumeric

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!!!");
}

Determining string length in Node JS when string may be null

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.

Categories

Resources