简体   繁体   中英

Array of strings adding commas when inserted into HTML

I have a bunch of names I'm adding to an array:

for (const approve of requestApproval[strings.Approve]) {
    approved.push(
        approve.Title + '<br/>'
    );
}

The array:

在此处输入图片说明

I then put it into an email as HTML:

<center>
    <table border="0" cellpadding="5" cellspacing="5" style = "border-collapse: collapse;">
        <tr>
            <th>Approved</th>
            <th>Abstained</th>
            <th>Not Approved</th>
        </tr>
        <tr>
            <td align="center">${approved}</td>
            <td align="center">${abstained}</td>
            <td align="center">${disapproved}</td>
        </tr>
    </table>
</center>

The result is a comma is inserted from somewhere:

在此处输入图片说明

How can I either stop the comma or remove the comma?

When you do this in your template literal:

<td align="center">${approved}</td>

... you silently convert the array approved to a string, whereby the array elements are delimited with a comma.

To avoid that, either:

  1. don't build an array, but a string:

     let approved = ""; // string! for (const approve of requestApproval[strings.Approve]) { approved += approve.Title + '<br/>'; } 

    Or

  2. convert the array in a controlled way, using the empty string as delimiter:

     <td align="center">${approved.join("")}</td> 

You need to convert your array to a string by joining it with empty strings ( .join('') ), otherwise, JavaScript will automatically join it with commas when converting it to a string.

You can also replace your for loop with Array.prototype.map() :

const approved = requestApproval[strings.Approve].map(x => x.Title + '<br/>').join('');

or (but removes the last <br> ):

const approved = requestApproval[strings.Approve].map(x => x.Title).join('<br/>');

Then insert the string in your html template string:

<td align="center">${approved}</td>

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