Definition and usage
The substring () method is used to extract characters of a string between two specified subscripts.
Syntax stringobject. substring (start, stop)
|
|
Start |
Required. A non-negative integer that specifies the position of the first character of the substring to be extracted in the stringobject. |
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: Unlike 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! "H is 0 document. write (Str. substring (3rd), 4, 5, 6 digits of four letters 7-3 = 4 so four letters contain 3 not contain 7 contain start not contain end </SCRIPT>
Output:
Lo w
<script> var ss = '1,e,2r,drf,dsfds,fdsfwf,'; var msg = ss.substring(0, ss.lastIndexOf(',')); alert(msg);