What is substring?
- end (optional): a number indicating the end position up to which the substring is copied
Extracting a substring from the beginning of a string
The following is an example of extracting a substring starting from the first position of the string:
Extracting the last characters of a string
The following is an example of extracting a substring from the specified index up to the end of the string:
Extracting a substring from the middle of a string
The following is an example of extracting a substring from the middle of a string:
The string.slice(start, end) and string.substring(start, end) methods are almost identical, but they differ in handling negative arguments.
|1. If the start is equal to the end an empty string is returned.
2. If the end is omitted, it will extract all characters from the start position to the end of the string.
3. If any of the arguments is greater than the length of the string, the length will be used instead.
4. Do not change the original string, but return a new string.
|1. If start > end, then substring() will swap these 2 arguments.
2. If any of the arguments is negative or equal to NaN, it is treated as if it were negative 0.
|1. If start > end, then slice() will return an empty string.
Extracting a substring from a string using the slice() method
The following is an example of how to extract a substring from a string using the slice() method: