Let’s discuss each of these methods in detail.
Syntax of substr() method
In the syntax, the parameter start refers to the position from where you want to extract the string and length refers to the number of characters you want to extract.
For better understandability see the following examples.
Let’s say we want to extract 5 letters from the first index. For doing so, the substr() method arguments would go like this:
The extracted string will be stored in the “result” variable. To verify, let’s log the “result” variable on the browser’s console:
As you can verify by looking at the output screenshot attached above that we have got our desired substring from the original string.
Now suppose you want to extract a different number of characters from a different position then you simply have to change the parameters.
Suppose you want to extract 3 characters only this time. The substr ( ) arguments would go like this.
For extracting the result we would do this.
The screenshot above shows the relevant code along with the output.
In order to extract parts of a string from the end position we use a negative value for the start position. Here is how you do it.
The output is shown in the following screenshot.
Now we will discuss the next string extraction method.
Syntax of substring( ) method
Following is the syntax of the aforementioned method.
By determining the syntax of the substring( ) method we can pinpoint the major dissimilarity between the substr( ) and substring( ) methods. The substr ( ) is used to extract a specific number of characters from a specified position while this substring() method is used to extract characters lying between the starting and ending positions of a string.
Let us demonstrate a substring( ) method example.
let result= text.substring(1,5);
In the following screenshot the output is demonstrated.
A few things that should be kept in mind while using the substring( ) method are as follows:
- Zero and negative values for start and end arguments are considered zero.
- If the value for the start parameter is more than the value of the end parameter then the parameters are swapped. For instance (5,1) will be swapped to (1,5).