Definition and usage
The substring () method is used to extract the character of a string intermediary between two specified subscripts.
Grammar
stringobject. substring (start,stop)
Parameters |
Description |
Start |
Necessary. A nonnegative integer that specifies the position of the first character of the substring to be extracted in the stringobject. |
Stop |
Optional. A nonnegative integer that is 1 more than the last character of the substring to extract in Stringobject. If this argument is omitted, the returned substring continues until the end of the string. |
return value
A new string value that contains a substring of Stringobject whose contents are all characters from start to stop-1, with a length of stop minus C12>start.
Description
The substring returned by the substring () method includes the character at start , but does not include the character at the stop .
If the argument start is equal to stop , the method returns an empty string (that is, a string of length 0). If start is larger than stop , the method swaps both parameters before extracting the substring.
Hints and Notes
Important: Unlike the slice () and substr () methods, substring () does not accept negative parameters.
Example 1
In this example, we will 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!
Try it yourself.
Example 2
In this example, we will 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
JavaScript substring () method