Table of Contents
- It returns part of a given string by the start index to the end index.
- The end index is excluded from the returning string
- If you do not provide an end index, it will take the end of the given string as the end index.
But, first, let’s be familiar with the syntax.
There are basically two ways that you can use the substring method
- substring(startIndex, endIndex)
The substring method takes two parameters.
startIndex: indicate the start position of the substring ( you need ) in the given string.
endIndex: indicate the end position of the substring in the given string.
As you can see the end position/index is optional.
Also, remember that the first index is at 0 ( zero )
The substring method will return a new string that is part of the given string from the start position to the end position EXCLUDING the character in the end position.
We will look at different uses of the substring method. Consider “WEB DEVELOPER” as the given string in the following examples.
const myStr = "WEB DEVELOPER";
Example 1: the start index is less than the end index
I would say that this is the typical use case that you would encounter in most situations.
console.log( myStr.substring(0, 3));//output "WEB"
The start index is 0, which contains “W”
The end index is 3, therefore the returning character is one before it, which is B. Remember the substring method excludes the character at the end position(which is a space in this example ).
Example 2: the start index equals the end index
console.log( myStr.substring(6,6));//output ""
The substring method returns an empty string
Example 3: the start index is greater than the end index
console.log( myStr.substring(3,0)); //output "WEB"
Substring methods take the start index( 3 ) as the end index and the end index( 0 ) as the start index. In other words, it swaps the given start and end indexes.
Let’s see some more uses
console.log( myStr.substring(-2,3));//output "WEB" console.log( mystr.substring(-3));//output "WEB DEVELOPER"
Any negative value for the start index is treated as a 0(zero ).
console.log( myStr.substring(4,20));//output "DEVELOPER"
If the parameter value for the end index is greater than the length of the string (myStr.length), it is handled as if it were equal to the length of the string.
Using substring with the String length property
Often you will be using this property as a parameter of the substring method.
const myStr = "WEB DEVELOPER"; console.log( myStr.substring( 4, myStr.length - 2 )); //output "DEVELOP", because myStr.substring( 4, 11 )
myStr.length is 13 as there are 13 characters in the string. Thus, the above example is the same as
myStr.substring( 4, 11 ).
I hope this post has given you a better understanding of how to use the