ホームページ > ウェブフロントエンド > jsチュートリアル > JavaScriptの文字列をサブストリングに分割する方法

JavaScriptの文字列をサブストリングに分割する方法

William Shakespeare
リリース: 2025-02-09 10:59:10
オリジナル
114 人が閲覧しました

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript String Splitting: substring() vs. split()</title>
</head>
<body>
    <h1>JavaScript String Splitting: `substring()` vs. `split()`</h1>

    <p>JavaScript offers two primary methods for dividing strings into substrings:  `substring()` and `split()`.  Each serves a distinct purpose.</p>

    <h2>`substring()`</h2>
    <p>The `substring()` method extracts a portion of a string based on starting and ending indices. It's ideal for retrieving a single substring from a known position within the string.</p>

    <p><strong>Syntax:</strong> <code>string.substring(startIndex, endIndex)</code></p>
    <ul>
        <li><code>startIndex</code>: The index of the first character to include (0-based).</li>
        <li><code>endIndex</code> (optional): The index *after* the last character to include. If omitted, the substring extends to the end of the string.</li>
    </ul>

    <p><strong>Example:</strong></p>
    <pre class="brush:php;toolbar:false"><code>
const str = "Hello, world!";
const sub = str.substring(7, 12); // Extracts "world"
console.log(sub); // Output: "world"
    
ログイン後にコピー

しばしば、 `indexof()`を使用して、開始インデックスまたは終了を動的に決定します。

`split()`

`split()`メソッドは、指定されたセパレーターに基づいて、文字列を一連のサブストリングに分割します。これは、文字によって区切られたアイテムのリストを含む文字列を処理するのに最適です(たとえば、コンマ分離された値)。

構文:

string.split(separator, limit)

    :文字列を分割するために使用される文字または文字列。
  • separator(オプション):戻るサブストリングの最大数
  • limit例:

重要な違い

<code>
const csv = "apple,banana,cherry";
const fruits = csv.split(","); // Splits at each comma
console.log(fruits); // Output: ["apple", "banana", "cherry"]
    </code>
ログイン後にコピー
いつ各メソッドを使用するか

Feature `substring()` `split()`
Output Substring (string) Array of substrings
Purpose Extract a portion at specific indices Split into multiple substrings based on a separator
Index-based Yes No (separator-based)
`substring()`を使用します。文字列内の既知の位置から単一の連続的なテキストを抽出する必要がある場合。

`split()`を使用します。コンマ、スペース、その他の文字など、区切り文字に基づいて文字列を複数の部分に分割する必要がある場合。

以上がJavaScriptの文字列をサブストリングに分割する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート