This article introduces three methods for extracting substrings in JS:
- substring() method;
- substr() method;
- slice() method;
Method 1: substring() method
string.substring(from, to)The method extracts from the from position to the to position. to is optional; if not set, it defaults to the end.
Example
Try it »
For more information about the substr() method, please refer to the documentation:http://www.example.com/jsref/jsref-substring.html。
Method 2: substr() method
substr() methodIt can extract the specified number of characters from the string, starting from the start index.
Example
Try it »
For more information about the substr() method, please refer to the documentation:http://www.example.com/jsref/jsref-substr.html。
Method 3: slice() method
The slice(start, end) method is used to extract a part of the string (from the start parameter to the end position), and returns the extracted part as a new string. Similar to substring().
Example
Try it »
For more information about the slice() method, please refer to the documentation:http://www.example.com/jsref/jsref-slice-array.html。