The substring() method extracts characters from start to end. The substring() method does not change the original string.
The indexStart parameter is required and is where to start the extraction. The first character is at index 0.
The indexEnd parameter is optional and 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 get the substring’s starting index of 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 the output will be.
// 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.
That’s it for this tutorial.