简体   繁体   中英

Can we use JS concat() inside Template literals (Template strings)?

I am trying to create a URL using Template Strings like -

a = {
    link: {
        pathname: `${url.split('?')[0]}${userId}/items?userType=${userId}}`
    },
};

The above snippet is working absolutely fine so is the below one. But should we use concat() inside Template strings like the below snippet or not?

a = {
    link: {
        pathname: `${url
            .split('?')[0]
            .concat(`${userId}/items?userType=${userId}`)}`,
    },
};

Why I used concat() because in my case, my enabled linting setup is throwing error for the first one as it should be written in two-lines, but it takes a new line or space as we give, which is not favorable in our case as we are creating URL.

If not, why? Just Curious.

Two answers for you:

  1. The content of a substitution ( ${...} ) can be any expression. It's fine to do method calls there.

  2. concat seems like an odd choice in that particular case, since there's no need for it. For that reason, from a style perspective, I'd use the first version. But it's a style thing, and you can use concat if you like. Note VLAZ's point that once you've done that, the whole expression is already producing the string you want and you have no need of a template literal at all.

So I'd either use your original:

a = {
    link: {
        pathname: `${url.split('?')[0]}${userId}/items?userType=${userId}}`
    },
};

or if you prefer concat :

a = {
    link: {
        pathname: url
            .split('?')[0]
            .concat(`${userId}/items?userType=${userId}`)},
    },
};

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