The substring() method returns a specified part of the string between start and end indexes.
Example
substring() Syntax
The syntax of the substring() method is:
str.substring(indexStart, indexEnd)
Here, str is a string.
substring() Parameters
The substring() method takes in:
- indexStart - The index of the first character to start including in the returned substring.
- indexEnd (optional) - The index before which to stop extraction. (Exclusive) If omitted, it extracts till the end of the string.
Notes:
- Any argument value < 0 is treated as 0.
- Any argument value > str.length is treated as str.length.
- Any
NaNargument value is treated as 0. - If
indexStartis greater thanindexEnd, the two arguments are swapped, i.e.str.substring(a, b)will bestr.substring(b, a).
substring() Return Value
- Returns a new string containing the specified part of the given string.
Note: substring() does not change the original string.
Example 1: Using substring
Output
P P JavaScript Tutorials nodmek JavaScript Tutorials nodmek JavaScript Tutorial
Example 2: Replacing a substring within a string
Output
JavaScript Tutorials
Recommended Reading: JavaScript String slice()