Which built-in method returns the characters in a string beginning at the specified location ?
- Using the substr() Method
- Using the slice() Method
We will explore these methods & will understand their implementation through the examples.
- start: It defines the index to start to extract the characters from the specified position and
- length: It defines the number of characters to be extracted starting from the start in the given string.
Return value: It returns a string that is the part of the given string. If the length is 0 or negative value then it returns an empty string.
Example: This example illustrates the concepts of the substr() method. In the first line, we have initialized a string, and called to substr() method with myString object. We have passed 2 as a starting index and 6 as the number of characters to be returned, then the ‘eksfor’ will be returned. If we have passed 5 as a starting index as we haven’t passed the second parameter, so, by default it will be considered till the end of the string and ‘forGeeks’ will be returned.
- beginIndex: It is the beginning index of the slice, including the first index.
- endIndex: It is the last index where to stop slicing, excluding the last index. By default, the endIndex is the string length.
Return: It returns a part or a slice of the given input string.
Example: This example illustrates the implementation of the slice() method. In the first line, we have initialized a string and called the slice() method by providing begin index as 2 and the last index is 6 so that it will return the characters from index 2 to 5 which are ‘eksf’. If we are calling the slice() method by providing the begin index as 5 and the end index will be taken as string length implicitly.