最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Join strings with a separator, ignoring empty strings - Stack Overflow

programmeradmin1浏览0评论

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 user663724user663724
Add a ment  | 

4 Answers 4

Reset to default 9

Not 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, filtering out all empty values and then joining 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

发布评论

评论列表(0)

  1. 暂无评论