[JavaScript]Converting Array Elements into a Single String with the join Method

目次

Overview

When you have data managed in an array and want to convert it into a single string—such as a CSV format (comma-separated) or a specific format like a slash-separated date—you use the join method. This approach is more efficient than using manual loops for string concatenation because it eliminates the need to handle the separator at the end of the string. This article explains how the method works using a network configuration tool for IP address generation as an example.

Specifications

The join method creates and returns a new string by concatenating all elements in an array, separated by a specified character string.

ArgumentDescription
separator (Optional)The character to insert between elements.
– Default: , (comma)
"" (empty string): No separator
  • Input: An array (can contain mixed types like numbers and strings).
  • Output: A concatenated string.

Basic Usage

1. Default Behavior (Comma Separator)

If you omit the argument, the elements are joined with a comma, similar to CSV data.

const metricPoints = [100, 200, 300];
console.log(metricPoints.join()); // "100,200,300"

2. Specifying a Separator (e.g., Slash)

This is commonly used for formatting date components.

const dateElements = [2026, 1, 15];
console.log(dateElements.join('/')); // "2026/1/15"

3. Direct Joining (Empty String)

If you want to join elements without any separator, specify an empty string.

const hexCodeParts = ['#', 'FF', '57', '33'];
console.log(hexCodeParts.join('')); // "#FF5733"

Full Code

The following example is a network configuration tool that retrieves values from four numeric input fields and concatenates them with a dot to generate an IP address string.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IP Address Generator</title>
    <style>
        .network-panel {
            font-family: 'Segoe UI', sans-serif;
            background-color: #f0f4f8;
            padding: 25px;
            border-radius: 8px;
            border: 1px solid #d1d9e6;
            width: fit-content;
        }
        .ip-inputs {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 15px;
        }
        .octet {
            width: 50px;
            padding: 8px;
            text-align: center;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 1rem;
        }
        .dot {
            font-weight: bold;
            color: #555;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result-box {
            margin-top: 15px;
            padding: 10px;
            background: #fff;
            border: 1px solid #ccc;
            font-family: monospace;
            color: #333;
            min-height: 1.2em;
        }
    </style>
</head>
<body>

<div class="network-panel">
    <h3>Network IP Configuration</h3>
    <div class="ip-inputs">
        <input type="number" class="octet" value="192" min="0" max="255">
        <span class="dot">.</span>
        <input type="number" class="octet" value="168" min="0" max="255">
        <span class="dot">.</span>
        <input type="number" class="octet" value="0" min="0" max="255">
        <span class="dot">.</span>
        <input type="number" class="octet" value="1" min="0" max="255">
    </div>
    
    <button id="btn-generate">Apply Settings (Join)</button>
    
    <div id="connection-log" class="result-box"></div>
</div>

<script src="ip_builder.js"></script>
</body>
</html>

JavaScript

/**
 * Network Configuration Script
 * Joins a numeric array using dots to generate an IP address
 */

const btnGenerate = document.getElementById('btn-generate');
const octetInputs = document.querySelectorAll('.octet');
const logArea = document.getElementById('connection-log');

/**
 * Logic to build the IP address string
 */
const buildIpAddress = () => {
    // 1. Retrieve values from input fields and create an array
    const octetValues = Array.from(octetInputs).map(input => {
        return input.value;
    });

    // octetValues will look like ["192", "168", "0", "1"]

    // 2. Concatenate with the join method
    // Use a dot as the separator
    const ipAddressString = octetValues.join('.');

    // Output the result
    logArea.textContent = `Generated IP: ${ipAddressString}`;
    console.log(`Target Address: ${ipAddressString}`);
};

btnGenerate.addEventListener('click', buildIpAddress);

Customization Points

Using a constant for the separator, such as const SEPARATOR = '.';, makes your code more resilient to specification changes, such as switching to a colon for MAC addresses. Additionally, handle your data carefully if the array contains null or undefined, as join will treat these as empty strings. It is safer to clean or format your data using map or filter before performing the join operation to prevent unintended data loss.

Notes

The result of the join method is always a string, even if the elements in the array are numbers. If you execute join on a nested array, such as [[1, 2], [3, 4]].join('-'), the inner arrays are converted to strings using the default comma separator, resulting in a string like "1,2-3,4". To control this behavior, you should use the flat method to flatten the array before joining it.

Applications

Generating breadcrumb navigation is a common use case. You can join the elements of an array representing the site structure with an arrow symbol to create a navigation string. For example, a path like ['Home', 'Products', 'Electronics'] joined with ' > ' results in "Home > Products > Electronics".

Summary

The join method is the most standard way to combine separate elements from an array into a single string. By choosing between the three patterns—omitting the argument for commas, specifying a character for custom separation, or using an empty string for direct connection—you can generate text in any format required for your application. This technique is essential for building robust text-based outputs from structured data.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次