JavaScript substring method
The substring method is used to intercept a string by specifying the start and end positions and return to intercept a partial string. The syntax is as follows:
The code copy is as follows:
str_object.substring(start, end)
| parameter | illustrate |
|---|---|
| str_object | String (object) to operate |
| start | Required. The position where the intercept is started, non-negative integer |
| end | Optional. The end position of the string intercept, non-negative integer; if omitted, until the end of the string |
Tip: If the parameter start and end are equal, then the method returns an empty string. If start is larger than end, the method will swap these two parameters before intercepting the string.
Substring method example
The code copy is as follows:
<script language="JavaScript">
var str = "abcdef";
document.write( str.substring(1, 3) + "<br />" );
document.write( str.substring(2, 2) + "<br />" );
document.write(str.substring(3, 1));
</script>
Run this example and output:
The code copy is as follows:
bc
bc
The difference between substring and slice and substr
1.substring cannot accept negative parameters, while slice method can
2. The second parameter of substring specifies the end of the intercept, while the second parameter of the substr method specifies the length of the intercept of the string