There is an object storing translation strings. The translation string can contain {user} noted placeholder to be used in the logic code:
const translations = {
...
'outOfQuota': 'Dear {userName}, you are out of space!'
}
The logic of the code that displays the message should show it when we have a userName:
Dear Jack, you are out of space!
However, there might be situations, when the user is logged in, but the user object is undefined or null. Also, sometimes userName can be undefined.
In such situation a slightly different message should be showed:
Dear, you are out of space!
Currently, I have solved it by removing the space between 'Dear' and the placeholder:
const translations = {
...
'outOfSpace': 'Dear{userName}, you are out of space!'
}
And writing a conditional logic to place the space and a name, or an empty string:
// Long code that results in setting:
const user.userName = 'John';
...
const userName = user && user.userName ? ` ${user.userName}` : ``; // (4)
const message = translations.outOfSpace.replace('{userName}', userName);
However, I don't like how line 4 and translation sentence looks like. It is hard to read.
Is there any way to make it look better?
question from:
https://stackoverflow.com/questions/65882523/how-to-put-a-conditional-space-between-words 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…