Below is the example of the String substr() Method.
- Example:
<script>
function
func() {
var
str =
'Geeks for Geeks'
;
var
sub_str = str.substr(6);
document.write(sub_str);
}
func();
</script>
- Output:
for Geeks
str.substr() method returns the specified number of characters from the specified index from the given string.
Syntax:
str.substr(start , length)
-
Perameters:
- start: It defines the starting index from where the substring is to be extracted from the base string.
- length: It defines the number of characters to be extracted starting from the start in the given string. If the second argument to the function is undefined then all the characters from the start till the end of the length are extracted.
Return value:
This method 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.
Examples for the above method are provided below:
Example 1:
var str = 'It is a great day.' print(str.substr(5));
Output:
a great day.
In this example the method substr() creates a substring starting from index 5 till the end of the string.
Example 2:
var str = 'It is a great day.' print(str.substr(5,6));
Output:
a gre
In this example the method substr() extracts the substring starting at index 5 and length of string is 6.
Example 3:
var str = 'It is a great day.' print(str.substr(5,-7));
Output:
In this example since the length of the string to be extracted is negative therefore the method returns an empty string.
Codes for the above method are provided below:
Program 1:
<script> // JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.' ; var sub_str = str.substr(5); document.write(sub_str); } func(); </script> |
Output:
a great day.
Program 2:
<script> // JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.' ; var sub_str = str.substr(5,6); document.write(sub_str); } func(); </script> |
Output:
a gre
Program 3:
<script> // JavaScript to illustrate substr() function function func() { // Original string var str = 'It is a great day.' ; var sub_str = str.substr(5,-7); document.write(sub_str); } func(); </script> |
Output: