str.substr() function returns the specified number of characters from the specified index from the given string.
Syntax:
str.substr(start , length)
Arguments:
The first argument to the function start defines the starting index from where the substring is to be extracted from the base string. The second argument to the function length 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 is extracted.
Return value:
This function 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 function are provided below:
Example 1:
var str = 'It is a great day.' print(str.substr(5));
Output:
a great day.
In this example the function 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 function 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 function returns an empty string.
Codes for the above function 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:
leave a comment
0 Comments