let fruits = 'Banana,Strawberry,Apple,Peach';//Length of fruitslet length = fruits.length;console.log('Length of fruits: ', length);//Without endIndex (default endIndex = length - 1)console.log('Without endIndex => ', fruits.substring(2));//startIndex and endIndex are same (returns empty string)console.log('Same startIndex & endIndex => ',fruits.substring(3,3));//index > length of the string (returns the length of the string)console.log('startIndex > length => ',fruits.substring(length+1));console.log('endIndex > length => ',fruits.substring(1,length+2));//startIndex > endIndex (indexes are swapped)console.log('startIndex > endIndex => ',fruits.substring(10, 2));//startIndex || endIndex === NaN (index is treated as 0)//startIndex || endIndex < 0 (index is treated as 0)console.log('Invalid indexes => ',fruits.substring(-1));console.log('Invalid indexes => ',fruits.substring(NaN));
00:48 Now there is another method to achieve the exact same result and that is the slice() method. It has the same syntax and accept the same two arguments, a start index and end index, and when we call slice() method on fruits string, it returns the exact same result. Now, what's the difference between the two? Let's look at few of them. With substring() method. If a start index is greater than the end index, which one would only do it by mistake, it swaps the start index with the end index. For example, Hello.substring(10,2) is the same as Hello.substring(2,10). It extracts the characters starting from index 2 till the end of the string and returns llo but with slice() method, if start index is greater than the end index, it returns an empty string. Let's look at this example.
01:34 If we call Hello.slice(10,2), it return an empty string. Next while using the substring() method, if the start or end index is not a number or a negative number, then that particular index is treated as zero. For example, calling Hello.substring(NaN) returns the entire string. This is because the start index is treated as zero and there is no end index, so all the characters till the end of the string are extracted and returned. Similar is the case with negative indexes. Any negative number that is passed as a start or end index will be treated as zero. Now with slice() method. The rule for passing, not a number is same as substring() method, but if the start or end index are negative, their corresponding values will be calculated as length of string plus start index and length of string plus end index depending upon which index was negative.