Home > Software engineering >  Conditionally include text between multiple values?
Conditionally include text between multiple values?

Time:06-02

I have this, which works, but some fields don't always have values (& don't render). Is there a way to include text conditionally? For example, between {a}, {b} & {c}, but only if they are both rendered?

const yay = `${a ? a   ` | `: ""}${b ? b   ` | ` : ""}${c ? c : ""}`

CodePudding user response:

You could use [a, b, c].filter(v => !!v).join('|'). This filters out all falsy values (undefined, null, false, 0, empty string, etc), which is what your current code is doing as well.

CodePudding user response:

You can add all of them in an array and filter them based on their truthy value evaluation in javascript. Later, just join the result as a string delimited by |.

let a = "789";
let b = "";
let c = true;

const result = [a,b,c].filter(ele => ele);

console.log(result.join('|'))

  • Related