[JavaScript]Splitting Strings by Delimiters and Converting to Arrays or Objects

目次

Overview

Processing text by breaking it down into manageable array formats based on specific rules (delimiters) is essential for tasks like analyzing CSV data or extracting URL parameters. This article explains how to use the String.prototype.split() method, covering everything from basic string splitting to practical implementations like parsing URL query strings into objects.

Specifications (Input/Output)

  • Input: A string representing a URL query (e.g., ?user_id=8823&theme=dark&active=true).
  • Output: An object containing the parsed keys and values (displayed as a list in HTML).
  • Operation:
    • Remove the leading ? and split the parameters by &.
    • Split each parameter into a key and value by =, then decode the strings.
    • Render the resulting object on the screen.

Basic Usage

Provide a delimiter (separator) as an argument to split(). The method returns an array of the separated strings.

const dateStr = "2026-01-24";
const parts = dateStr.split("-");
console.log(parts); // ["2026", "01", "24"]

// Specifying an empty string splits the text character by character
const word = "Code";
console.log(word.split("")); // ["C", "o", "d", "e"]

Full Code (HTML / JavaScript)

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String Split Example</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .result-box {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 15px;
            border-radius: 4px;
            margin-top: 10px;
        }
        ul { margin: 0; padding-left: 20px; }
        code { background: #eee; padding: 2px 4px; border-radius: 2px; }
    </style>
</head>
<body>

    <h2>URL Parameter Analysis</h2>
    <p>Target String: <code id="targetUrl">?product=laptop&category=pc&ref=google</code></p>
    
    <div id="outputArea" class="result-box">
        Displaying analysis results...
    </div>

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

JavaScript

/**
 * Function to parse a query string and convert it into an object
 * @param {string} queryString - The string to analyze (e.g., "?a=1&b=2")
 * @returns {Object} An object containing key-value pairs
 */
const parseQueryString = (queryString) => {
    // 1. Remove the leading "?" (only if it exists)
    const paramsStr = queryString.startsWith("?") 
        ? queryString.slice(1) 
        : queryString;

    if (!paramsStr) return {};

    // 2. Split into parameter blocks using "&"
    // Example: ["product=laptop", "category=pc", "ref=google"]
    const paramPairs = paramsStr.split("&");

    const result = {};

    paramPairs.forEach((pair) => {
        // 3. Split into key and value using "="
        // We find the first index of "=" to handle cases where the value might contain "="
        const splitIndex = pair.indexOf("=");
        
        if (splitIndex === -1) return; // Skip if no "=" is found

        const key = pair.slice(0, splitIndex);
        const rawValue = pair.slice(splitIndex + 1);

        // URL decoding process
        result[key] = decodeURIComponent(rawValue);
    });

    return result;
};

// Execution logic
const init = () => {
    const targetElement = document.getElementById("targetUrl");
    const outputElement = document.getElementById("outputArea");
    
    const inputString = targetElement.textContent;
    
    // Run the analysis
    const parsedData = parseQueryString(inputString);
    
    // Generate results as an HTML list
    const listHtml = Object.entries(parsedData)
        .map(([key, value]) => `<li><strong>${key}</strong>: ${value}</li>`)
        .join("");
        
    outputElement.innerHTML = `<ul>${listHtml}</ul>`;
    
    console.log("Analysis result object:", parsedData);
};

document.addEventListener("DOMContentLoaded", init);

Customization Tips

  • Splitting with Regular Expressions: You can pass a regular expression to split() instead of a string. For example, to split by both commas and spaces, use text.split(/[\s,]+/);.
  • Removing Empty Elements: If the split results in empty strings (e.g., splitting data,,data by a comma), you can chain .filter(item => item) after the split() method to remove unwanted empty elements from the array.

Important Notes

  • Splitting Surrogate Pairs (Emojis): Using "".split("") to split a string character by character will break surrogate pairs (e.g., 🍎), resulting in garbled text. To split strings containing emojis properly, use the spread syntax: [...str].
  • Behavior of the Split Limit: While you can specify a maximum number of splits using split(separator, limit), the remaining part of the string is discarded rather than kept together. This differs from methods like explode in languages like PHP.

Advanced Usage

Specifying the Number of Splits

In cases like log data where you want to separate a “date” from the “rest of the message” at the first occurrence of a space, it is often better to combine indexOf and slice.

const logLine = "2026-01-24 [ERROR] System crashed";

// To split only at the first space and keep the rest intact
const firstSpace = logLine.indexOf(" ");
const date = logLine.slice(0, firstSpace);
const message = logLine.slice(firstSpace + 1);

console.log(date);    // "2026-01-24"
console.log(message); // "[ERROR] System crashed"

Summary

The split() method is a powerful tool not just for simple string separation but as the first step in structuring and analyzing data. It is ideal for data with clear delimiters. However, for strings containing emojis or complex nested structures, consider using the spread syntax or specialized parsers (like JSON analysis) instead. Selecting the right splitting technique ensures robust data processing.

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

この記事を書いた人

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

目次