简体   繁体   中英

How can I remove empty strings in template literals?

I'm creating a script that loops through an array of objects and creates .edn file that we're using to migrate some of our client's data.

As we have to use .edn file which uses Clojure , I generate a template literal string and populate the data in the format that we need.

In the generated string I have many conditional operations, where I check if some data exist before returning some string. If the data doesn't exist I cannot use null, so I use an empty string. Now when my file gets created, those empty strings create an extra line that I want to remove. Investigating it more, the string adds /n which actually creates those extra lines from an empty string.

What is the best way to do it?

This is an example of what I'm doing:

arrayOfObjects.map(a => {
   return `
    ; ...other code that doesn't depend on data
   
    ; Code that depends on data, if it's false I want to remove it completely and
    ; and avoid passing empty string as it creates extra space in the generated file
        ${a.stripe_connected_account
            ? `[[:im.stripeAccount/id]
                #:im.stripeAccount{:stripeAccountId "${a.stripe_connected_account}"
                  :user #im/ref :user/${a.user}}]`
            : ""}   
`;
});

Appreciate any help, thanks!

An empty string doesn't do that. T${''}h${''}i${''}s is no different from This . The "extra space" is the whitespace that you (unconditionally) include in your template string around the ${ } part:

If you'd start the ${ } expression earlier and end it later and put the whitespace (if you even want it) as part of your if-true expression of the ternary, you will get what you want.

For example:

arrayOfObjects.map(a => {
  return `
    ; ...other code that doesn't depend on data
   
    ; Code that depends on data, if it's false I want to remove it completely and
    ; and avoid passing empty string as it creates extra space in the generated file${
      a.stripe_connected_account ? `
    [[:im.stripeAccount/id]
    #:im.stripeAccount{:stripeAccountId "${a.stripe_connected_account}"
    :user #im/ref :user/${a.user}}]`
      : ""
  }`;
});

(Yes, the strange indentation is a result of merging two different indentation levels, the code's and the output's, and preventing line breaks in the output unless desired. I tried several ways to format it but none of them looked good - there are only ugly ways, no way to indent it nicely and have the result you want, unless you were to write a tagged template function that would smartly detect when a ${ } expression would need surrounding whitespace stripped and when it wouldn't.)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM