The substring() extracts characters from indexStart up to but not including indexStart in particular. If an indexEnd is omitted, then the substring() extracts characters to the end of a string. If an indexStart is equal to the indexEnd, then the substring() returns an empty string.
The indexStart parameter is required, and it is the position where to start the extraction. The first character is at index 0.
The indexEnd parameter is optional, and it is the position where to end the extraction. If omitted, it extracts the rest of the string.
The example is the following.
// app.js let str = 'Obama was US president'; let newstr = str.substring(0,5); console.log(newstr);
In the above example, we are getting the substring’s starting index 0 and go to 5. So the substring() becomes the Obama.
The substring with a length property
The below example uses a substring() method and the length property to extract the last characters from a particular string.
// app.js let str = 'Obama was US president'; let newstr = str.substring(str.length-10); console.log(newstr);
If we do not specify the second parameter
Let us take a scenario where we do not specify the indexEnd and see what will be the output.
// app.js let str = 'Obama was US president'; let newstr = str.substring(5); console.log(newstr);
Any argument value that is less than 0 or greater than the length of a string is treated as if it were 0 and stringName.length respectively.
Any argument value that is NaN is treated as if it were 0.