📜  js .substring - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:28.628000             🧑  作者: Mango

js .substring - Javascript

Introduction

In JavaScript, the substring method is used to extract a portion of a string and return a new string containing the extracted characters. It is a commonly used method for manipulating strings in JavaScript.

Syntax

The syntax for using the substring method is as follows:

string.substring(startIndex, endIndex)
  • string: The original string from which the substring will be extracted.
  • startIndex: The index at which the extraction should begin. It is a zero-based index, meaning the first character has an index of 0.
  • endIndex: Optional parameter specifying the index at which the extraction should end. The character at this index is not included in the substring. If not provided, the substring will extend to the end of the original string.
Return Value

The substring method returns a new string that consists of the characters extracted from the original string.

Examples

Here are a few examples to demonstrate the usage of the substring method:

Example 1: Extracting a Substring Starting from a Specific Index
const str = "Hello, World!";
const substring = str.substring(7);

console.log(substring);

Output:

World!

In this example, the substring method is called on the string "Hello, World!" with the startIndex parameter set to 7. This means that the substring will start from the character at index 7, which is 'W'. The extracted substring "World!" is then printed to the console.

Example 2: Extracting a Substring within a Specific Range
const str = "Hello, World!";
const substring = str.substring(7, 10);

console.log(substring);

Output:

Wor

In this example, the substring method is called on the string "Hello, World!" with both startIndex and endIndex parameters specified. The startIndex is set to 7, and the endIndex is set to 10. This means that the substring will start from the character at index 7 and end at the character at index 9, which is 'o'. The extracted substring "Wor" is then printed to the console.

Note
  • If the startIndex is greater than the endIndex, the substring method will swap the two values before extracting the substring.
  • If either startIndex or endIndex is negative or exceeds the length of the string, JavaScript will treat it as if it was equal to the string's length.

For more details about the substring method, refer to the MDN documentation.

Markdown格式: markdown (代码片段)