I am trying to form a variable.
If it is not null
or empty or undefined
I don't want to append the @
symbol to it:
var T1 = 'Popcorn'
var T2 = 'Icecreams'
var T3 = '';
var T4 = '';
if(T1!=''||T2!=''||T3!=''||T4!='')
reqstr = T1+'@'+T2+'@'+T3+'@'+T4;
alert(reqstr);
Right now the output is:
Popcorn@Icecreams@@
If the variable is empty I don't want to append @
, meaning I require only:
Popcorn@Icecreams
Fiddle.
I am trying to form a variable.
If it is not null
or empty or undefined
I don't want to append the @
symbol to it:
var T1 = 'Popcorn'
var T2 = 'Icecreams'
var T3 = '';
var T4 = '';
if(T1!=''||T2!=''||T3!=''||T4!='')
reqstr = T1+'@'+T2+'@'+T3+'@'+T4;
alert(reqstr);
Right now the output is:
Popcorn@Icecreams@@
If the variable is empty I don't want to append @
, meaning I require only:
Popcorn@Icecreams
Fiddle.
Share Improve this question edited Oct 27, 2014 at 11:36 the swine 11k8 gold badges63 silver badges105 bronze badges asked Oct 27, 2014 at 11:00 user663724user6637244 Answers
Reset to default 9Not the clearest Q.; try this:
[T1,T2,T3,T4].filter(Boolean).join('@');
And if you want to allow numbers in your variables, you need to do a bit more work:
[T1,T2,T3,T4].filter(function(x){
return typeof x === 'number' || x;
}).join('@');
And to allow numbers, but filter out NaN
:
[T1,T2,T3,T4].filter(function(x){
return x === 0 || x;
}).join('@');
Etc., depending on the specification.
Try this:
if(T1!=''||T2!=''||T3!=''||T4!=''){
reqstr = T1+'@'+T2+'@'+T3+'@'+T4;
reqstr = reqstr.replace(/@@/g, '@').replace(/(^@+)|(@+$)/g, '')
}
The first replace
removes all double @
's from the string. The second one removes any leading or trailing ones.
try this
var T1 = 'Popcorn'
var T2 = 'Icecreams'
var T3 = '';
var T4 = '';
reqstr = (T1)?(T1+'@'):'';
reqstr += (T2)?(T2+'@'):'';
reqstr +=(T3)?(T3+'@'):'';
reqstr +=(T4)?(T4+'@'):'';
console.log(reqstr);
alert(reqstr);
You could try putting the variables into an array, filter
ing out all empty values and then join
ing it using @
as a separator.
var T1 = 'Popcorn'
var T2 = 'Icecreams'
var T3 = '';
var T4 = '';
var arr = [T1, T2, T3, T4];
arr = arr.filter(function(e){ return e;}); // The filtering function returns `true` if e is not empty.
reqstr = arr.join("@")
console.log(reqstr);
alert(reqstr);
JSFiddle