ArticleDirectory
- Syntax
- Return Value
- Description
- Example 1
- Example 2
Definition and usage
The substring () method is used to extract characters of a string between two specified subscripts.
Syntax
Stringobject. substring (start, stop)
Parameters
Start: required. A non-negative integer that specifies the position of the substring to be extracted in the stringobject of the first character.
Stop: Optional. A non-negative integer is 1 more than the position of the last character of the substring to be extracted in the stringobject. If this parameter is omitted, the returned substring ends at the end of the string.
Return Value
A new string. The value of this string contains a substring of stringobject. Its content is all characters from start to stop-1, and its length is stop minus start.
Description
The substring returned by the substring () method includes the start character, but not the end character.
If the start and end parameters are equal, the method returns an empty string (a string with a length of 0 ). If start is greater than end, this method swaps the two parameters before extracting the substring.
Tips and comments
Important:Different from slice () and substr (), substring () does not accept negative parameters.
Example 1
In this example, we use substring () to extract some characters from the string:
<SCRIPT type = "text/JavaScript"> var STR = "Hello world! "Document. Write (Str. substring (3) </SCRIPT>
Output:
Lo world!
Example 2
In this example, we use substring () to extract some characters from the string:
<SCRIPT type = "text/JavaScript"> var STR = "Hello world! "Document. Write (Str. substring (3,7) </SCRIPT>
Output:
Lo w
Tiy
-
Substring ()
-
How to extract some characters from a string using substring.