Substring() function in Javascript
A substring() function returns extracted part of string from the specified index and returns new extracted string without affecting an existing string. A string index starts from 0 as first characters. The main difference between substring() and slice(), if start index and end index specified less than 0 are treated as 0 in substring(). A substring() end index value is optional, if skipped it will consider as end of string.
Syntax
 1 <string_object>.substring(<start_position>, <end_position>)
string_object : A string object from which we want to extract sub string
start_position : A starting position from where we want to extract string, if negative value provided as starting position, it considered as 0
end_position : It is optional and if specified, it extract string till specified index, if negative value provided as starting position, it considered as 0
substring() function
 1 let str = "Hello world ! ";
 2 	
 3 let extracted = str.substring(5, 10); // returns ' worl'
 4 	
 5 let extracted = str.substring(-5, 10); // returns 'Hello worl'
 6 	
 7 let extracted = str.substring(5); // returns ' world ! '
In the above example, we have define string variable with initial value. The first example, extract the string from index value 5 to index value 10. The second example, extract the string starting from index 0 as negative value considered as 0 to 10. The third example, extract string starting from index 5 till the end of string, as ending value is omitted.

String substring() with array

String substring() with array
 1 function print(array, len) {
 2     for(str of array) {
 3         console.log(str.substring(0, len))
 4     }
 5 }
 6 
 7 let arr = [
 8     "this is string slice function",
 9     "Print hello world in function",
 10     "IOgyan to tutorial"]
 11     
 12 // calling function, print 20 characters
 13 print(arr, 20)
In the above example, an array of string is define and initialized with string literals. A print() function is define that accepts two parameters array and length of string to create substring. It iterates array and prints specified length substring from an array.
Output
 1 this is string slice
 2 Print hello world in
 3 IOgyan to tutorial
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us