Is there a way to do conditional within a template string?
For example:
let x, y;
x = ...
y = ...
let templateString = `${x} ${y}`;
I don't want the space in the template string after x to be output if y is undefined. How would I achieve that with template string?
Is this the only way to do it?
let templateString = `${x}${y ? ' ' + y : ''}`;
What about
let x,y;
const templateString = [x,y].filter(a => a).join(' ');
What it does that it first puts your properties into an array [].
Then it filters the undefined items.
The last it creates a string of the array, by using join
with a space.
This way either x
or y
can be undefined.
如果您不在模板中添加逻辑,看起来会更容易阅读:
let templateString = y ? `${x} ${y}` : `${x}`;
使用嵌套模板文字的另一种稍微简洁的方法。
`${x}${y ? ` ${y}` : ''}`
It's probably overkill for this small example, butTagged template functions provide a nice general solution that allow an amazing amount of flexibility while keeping your template strings clean. For example here's one that will remove text preceding an undefined variable in general:
function f(str ,...variables){ return variables.reduce((res, v, i) => v ? res + str[i] + v: res, '') } let x, y, z; x = "test" y = "test2" // both defined console.log(f`${x} + ${y}`) // only one: console.log(f`${x} + ${z}`) // random text: console.log(f`${x} with ${z} and ${y}`)
Since it passes everything to a function, you can do almost any logic you want while still having readable strings. There's some documentation about halfway down the MDN Page on template literals .
technically you can nest these template strings, its not pretty but this works
let templateString = `${y ? `${x} ${y}`: `${x}`}`;
i would use the solution from the first comment though.
You can also use functions inside expressions
Here is an example of it
let x, y; x = 'test' y = undefined; let templateString = `${x} ${y}`; function fn(value1,value2) { return value2? (value1 + ' ' + value2) : value1 } console.log('when undefined =',`${fn(x,y)}`); x = 'test' y = 'test1'; console.log('when not undefined = ',`${fn(x,y)}`);
甚至更好
const templateString = `${x} ${y}`.trim();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.