How to generate a comma separated string from array in JavaScript

Use the arr.join([separator]) function. The separator specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (“,”). If separator is an empty string, all elements are joined without any characters in between them.

    private generateBlogPostHeader(commaSeparatedListOfTags: string, snippet: Snippet): string {
        let header: string = '';

        header += 'categories: [snippets]\n';
        header += `tags: [${snippet.tags.join(',')}]\n`;
        header += '---\n';

        return header;
    }

You can also use the toString() method in this particular case with the same result

header += `tags: [${snippet.tags.toString()}]\n`;

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

routerLink with query params in Angular html template

routerLink with query params in Angular html template code snippet Continue reading