JavaScript substring()

Created with Sketch.

JavaScript substring()

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 JavaScript String.prototype.substring() returns the part of the string between the start and end indexes:

str.substring(startIndex [, endIndex])

Code language: JavaScript (javascript)

The substring() method accepts two parameters: startIndexand endIndex:

  • The startIndex specifies the index of the first character to include in the returned substring.
  • The 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).

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 domain from the email example

The following example uses the substring() with the indexOf() to extract the domain from the email:

let email = 'john.doe@gmail.com';
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() returns the substring from a string between the start and end indexes.

Leave a Reply

Your email address will not be published. Required fields are marked *