The substring()
method in JavaScript returns a portion of a string and is used to get substrings.
There are two variants for substring()
method implementation in JavaScript.
We specify a start index and the returned substring includes​ characters starting from the specified start index of the input string, until the end of the string.
stringName.substring(var startIndex)
A visualization​ of this is shown below:
You can edit the code, written between the <script>
</script>
tags above and see how the output changes.
We specify the start index and the end index. The returned substring includes characters including and between the specified indexes. The character at the start index is included in the substring, however, the character at the end index is not. So, the characters in the extracted substring begin from the start index till the end index-1.
stringName.substring(var startIndex, var endIndex)
A visualization of this is shown below:​
You can edit the code, written between the <script>
</script>
tags above and see how the output changes.
Note:
substring()
method does not change the original string.
Substring extraction is useful for prefix and suffix extraction. For example, it is helpful in extracting the family name from a name.
Free Resources