Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - How to put a conditional space between words?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Make it a function. You can make it a one line code in es6

const translations = {
   ...,
   outOfQuota: function(name){
   return `Dear${name ? ` ${name}`: ""}, you are out of space!`
 }
}

you can also add a default val in the arg when its undefined


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...