In this tutorial, you’ll learn how to use the JavaScript
substring()
method to extract a substring from a string.
The JavaScript String.prototype.substring()
returns the part of the string between the start and end indexes:
str.substring(startIndex [, endIndex])
The substring()
method accepts two parameters: startIndex
and endIndex
:
startIndex
specifies the index of the first character to include in the returned substring.endIndex
determines the first character to exclude from the returned substring. In other words, the returned substring doesn’t include the character at the endIndex.If you omit the endIndex
, the substring()
returns the substring to the end of the string.
If startIndex
equals endIndex
, the substring()
method returns an empty string.
If startIndex
is greater than the endIndex
, the substring()
swaps their roles: the startIndex becomes the endIndex and vice versa.
If either startIndex
or endIndex
is less than zero or greater than the string.length
, the substring()
considers it as zero (0) or string.length
respectively.
If any parameter is NaN
, the substring()
treats it as if it were zero (0).
Let’s take some examples of using the JavaScript substring()
method.
#javascript #programming #developer #web-development