Open In App

Which built-in method returns the characters in a string beginning at the specified location ?

In this article, we will know how to return the required sequence of characters in a string, beginning from a specified position, in Javascript. There are 2 built-in methods to accomplish this task:

We will explore these methods & will understand their implementation through the examples.



JavaScript substr() Method: The substr() Method built-in method that is used to return the characters in a string beginning at the specified location, 

Syntax:



str.substr(start, length);

 

Parameters:

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.




<script>
    let myString = "GeeksforGeeks";
    let returnedStr1 = myString.substr(2, 6);
    console.log(returnedStr1);
    let returnedStr2 = myString.substr(5);
    console.log(returnedStr2);
</script>

Output:

Javascript substr() Method

JavaScript slice() Method: The slice() method is a built-in method that is used to create the slice of any string and then it returns the new string without affecting the original one.

Syntax:

str.slice(beginIndex, endIndex);

Parameter: The

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. 




<script>
    let myString = "GeeksforGeeks";
    let returnedStr1 = myString.slice(2, 6);
    console.log(returnedStr1);
    let returnedStr2 = myString.slice(5);
    console.log(returnedStr2);
</script>

Output:

Javascript slice() Method


Article Tags :