<code class="language-html"><!DOCTYPE html> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript String Splitting: substring() vs. split()</title> <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" </code>
>通常,您会使用`indexof()`来动态确定开始索引或结束索引。
'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) |
以上是如何将字符串分为JavaScript中的子字符串的详细内容。更多信息请关注PHP中文网其他相关文章!