Summary: in this tutorial, you’ll learn how to use the JavaScript substring()
method to extract a substring from a string.
Introduction to the JavaScript substring() method
The substring()
method returns the part of the string from the start index (startIndex
) up to and excluding the end index (endIndex
):
str.substring(startIndex [, endIndex])
Code language: JavaScript (javascript)
The substring()
method accepts two parameters: startIndex
and endIndex
:
- The
startIndex
specifies the index of the first character to include in the returned string. - The
endIndex
determines the first character to exclude from the returned substring. In other words, the returned substring doesn’t include the character at theendIndex
.
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).
JavaScript substring() examples
Let’s take some examples of using the JavaScript substring()
method.
1) Extracting a substring from the beginning of the string example
The following example uses the substring method to extract a substring starting from the beginning of the string:
let str = 'JavaScript Substring';
let substring = str.substring(0,10);
console.log(substring);
Code language: JavaScript (javascript)
Output:
JavaScript
Code language: JavaScript (javascript)
2) Extracting a substring to the end of the string example
The following example uses the substring() to extract a substring from the index 11 to the end of the string:
let str = 'JavaScript Substring';
let substring = str.substring(11);
console.log(substring);
Code language: JavaScript (javascript)
Output:
Substring
Code language: JavaScript (javascript)
3) Extracting the domain from the email example
The following example uses the substring()
with the indexOf()
to extract the domain from the email:
let email = '[email protected]';
let domain = email.substring(email.indexOf('@') + 1);
console.log(domain); // gmail.com
Code language: JavaScript (javascript)
How it works:
- First, the
indexOf()
returns the position of the@
character. - Then the substring returns the domain that starts from the index of
@
plus 1 to the end of the string.
Summary
- The JavaScript
substring()
method returns the substring from the start index up to and excluding the end index.