>웹 프론트엔드 >JS 튜토리얼 >JavaScript에서 문자열을 하위 문자로 분할하는 방법

JavaScript에서 문자열을 하위 문자로 분할하는 방법

William Shakespeare
William Shakespeare원래의
2025-02-09 10:59:10146검색
<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 ()` `split ()`메소드는 지정된 분리기를 기반으로 문자열을 일련의 하위 문자로 나눕니다. 이것은 문자로 구분 된 항목 목록을 포함하는 문자열을 처리하는 데 적합합니다 (예 : 쉼표로 구분 된 값). 구문 :

: 문자열을 나누는 데 사용되는 문자 또는 문자열.

(선택 사항) : 반환 할 최대의 하위 문자열 수

예 :

주요 차이점 각 메소드를 사용하는시기 string.split(separator, limit)

사용`substring ()`문자열 내에서 알려진 위치에서 단일 연속 텍스트 조각을 추출해야 할 때. ``split ()`를 사용하십시오. 쉼표, 공간 또는 기타 문자와 같은 구분기를 기반으로 문자열을 여러 부분으로 나누어야 할 때.
  • separator

위 내용은 JavaScript에서 문자열을 하위 문자로 분할하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.