String & substring
A string is simply a text or characters which can include alphabets, numbers, or symbols.
A substring, as it’s in its name. A subpart of a String.
The syntax for the substring() function is
startIndex is the index from where you want to start the string.
endIndex is the index where you want to end the string.
Now, if you notice that it doesn’t include the 5th index element. But, it picked the 0th index element. Which implies that startIndex gets included. While endIndex doesn’t get included.
So, now if we want to pick the “hint” from “linuxhint”. Although there are only “0” to “8” indexes. But, we will give “9” as a value to the endIndex.
We can give it only one value as well.
It will start from that index and continues until the end of the string.
Alright! Now, we have seen the syntax and how does it work. Let’s see some of its exceptional cases.
Let’s try to give a startIndex greater than the endIndex and some negative values to see how does it respond.
startIndex > endIndex
If we give it a startIndex greater than the endIndex.
It has swapped both values and printed the string from the 2nd index to the 5th index.
So, if we write either name.substring(5, 2) or name.substring(2, 5).
name.substring(5, 2); // “nux”
name.substring(2, 5); // “nux”</td>
It will print out the same output.
substring() function doesn’t take negative values. If we give it a negative value. Since there is no negative index. It takes it as a “0”. Either we give a negative value to the startIndex or the endIndex. This function considers it a “0”.
If we give a negative value to the endIndex. The function will swap the values. Because negative value will be converted to “0” and “0” will be the lowest value.
And, if we give a negative value to both of the indexes. The function will print an “” empty string.
By the way, here is a pro tip. We can use string.length function within a substring() function.
Or we can give it a string.length – [value], like
So, after reading this article, you should have a profound knowledge of the substring() function. Because you have learned all about the substring() function. All of its exceptional cases and how can we manipulate the string according to our needs. So, have fun with the strings.