Reputation: 46322
In javascript I have the following:
var inf = id + '|' + city ;
if id or city are null then inf will be null.
Is there any slick way of saying if id or city are null make then blank.
I know in c# you can do the following:
var inf = (id ?? "") + (city ?? "");
Any similar method in javascript?
Upvotes: 7
Views: 26819
Reputation: 3114
function nullToStr(str) {
return !str || 0 === str.length ? '' : str;
}
usage:
console.log(nullToStr(null);
function nullToStr(str) {
return !str || 0 === str.length ? '' : str;
}
console.log(`The value which was null = ${nullToStr(null)}`);
console.log(`The value which was null = ${nullToStr(undefined)}`);
console.log(`The value which was null = ${nullToStr('')}`);
console.log(`The value which was null = ${nullToStr('asdasd')}`);
I think it will help and is much easier to use. Obviously, it is based on the other answers i found in this thread.
Upvotes: 1
Reputation: 13
if (id != ""){
inf = id;
if (city != ""){ inf += " | " + city ;}
}
else
inf= city;
Upvotes: 0
Reputation: 122986
Equivalent to c# var inf = (id ?? "") + (city ?? "");
(if id
and city
are nullable) is
var inf = (id || '') + (city || '');
This is referred to as 'Short-Circuit Evaluation'. Nullability is not an issue in javascript (in js all variables are nullable), but id
and city
have to be assigned (but do not need a value, as in var id, city
).
Upvotes: 0
Reputation: 7212
How about:
var inf = [id, city].join('|');
EDIT: You can remove the "blank" parts before joining, so that if only one of id and city is null, inf will just contain that part and if both are null inf will be empty.
var inf = _([id, city]).compact().join('|'); // underscore.js
var inf = [id, city].compact().join('|'); // sugar.js
var inf = [id, city].filter(function(str) { return str; }).join('|'); // without helpers
Upvotes: 22
Reputation: 1445
var inf = (id == null ? '' : id) + '|' + (city == null ? '' : city)
Upvotes: 5
Reputation: 53361
Total long shot, but try this:
var inf = (id || "") + "|" + (city || "");
Upvotes: 16