The substring methods returns a certain section of the original string based on the parameters in the function. There are two methods for substring,
substring(). The syntax and the function of each method is shown below.
- returns a substring, starting from index
- returns a substring, starting from
startand ending at
endis optional if
endis equal to the length of the string
The code sample above shows the use of both
substr() method creates a new string that consists of 5 characters starting from index 0 of the original string. Therefore, only "Hello" is printed on the first line. The
substring() method creates a new string starting from the 6th index all the way to the last index of the string, 12. This prints "World!" on the console. As mentioned previously, the
end parameter of the
substring() method is not necessary if
end is equal to the length of the string. Try removing the "12" from the method and see if the output is the same.