📅  最后修改于: 2023-12-03 14:43:28.628000             🧑  作者: Mango
js .substring - Javascript
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.
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.The substring
method returns a new string that consists of the characters extracted from the original string.
Here are a few examples to demonstrate the usage of the substring
method:
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.
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.
startIndex
is greater than the endIndex
, the substring
method will swap the two values before extracting the substring.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 (代码片段)