Example of getting started with the substring method of a JavaScript string object (used to intercept strings) and a javascript string
JavaScript substring Method
The substring method is used to intercept a string by specifying the start and end positions and return part of the string. The syntax is as follows:
Copy codeThe Code is as follows:
Str_object.substring (start, end)
| Parameters |
Description |
| Str_object |
String (object) to be operated) |
| Start |
Required. Position where the truncation starts. It is a non-negative integer. |
| End |
Optional. The position where the string is truncated. It is a non-negative integer. If it is omitted, it ends until the string ends. |
Tip: If the start and end parameters are the same, the method returns an empty string. If start is greater than end, this method swaps the two parameters before intercepting the string.
Substring Method Instance
Copy codeThe Code 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:
Copy codeThe Code is as follows:
Bc
Bc
Differences between substring, slice, and substr
1. substring cannot accept negative parameters, while the slice method can
2. The second parameter of substring is to specify the position at which the truncation ends, while the second parameter of the substr method is to specify the length of the string truncation.
Question about string Truncation in JavaScript substring
Both a and c are correct. You can parse the script in the browser to understand it.
String truncation, subString () method
Two methods
1. If you want to get the content before the file extension, you do not need to use substring.
String str = "index. do". split ("\.") [0] // index
Split the character into an array by point, and retrieve the first element of the array.
2. If you do not use substring
String str = "index. do". substring (0, "index. do". indexOf ("."));