Nate Pet
Nate Pet

Reputation: 46322

javascript null value in string

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

Answers (7)

Steve Johnson
Steve Johnson

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

ouday khaled
ouday khaled

Reputation: 13

if (id != ""){
inf = id;
if (city != ""){ inf += " | " + city ;}
}
else 
inf= city;

Upvotes: 0

KooiInc
KooiInc

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

psyho
psyho

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

xdazz
xdazz

Reputation: 160943

var inf = (id && city) ? (id+"|"+city) : "";

Upvotes: 0

Philipp
Philipp

Reputation: 1445

var inf = (id == null ? '' : id) + '|' + (city == null ? '' : city)

Upvotes: 5

Elliot Bonneville
Elliot Bonneville

Reputation: 53361

Total long shot, but try this:

var inf = (id || "") + "|" + (city || "");

Upvotes: 16

Related Questions