The JavaScript substring method

The substring method is used to get the substring of a given string by specifying the start and end numbers.

The starting index is the number of character in the given string that will be included to get the substring. Whereas end number will not be included in the substring JavaScript method.

Syntax of JavaScript substring method

Following is the syntax of using the substring method:

Str.substring(start_index, end_index);

A substring example

A few points about substring JS method are:

  • start_index is mandatory, that specifies where to start extracting a substring.
  • end_index is optional, if not specified the substring will go to the end of given string.
  • if start_index is greater than the end_index value, the order will be inverted i.e. end_index becomes start index.
  • The original string remains the same after using the substring method.

e.g. str_substring = str(5,10);

Let us look at a few examples of using substring method now.

A substring example with both indices

Following example uses both indices in the JavaScript substring method. We will specify start and end index to a string variable and assign it to another string variable. As you click on the button “Show Substring” it will show substring value.

Experience this example online

We used 5 and 18 indices that returned “is javascript” substring from the original string.

Substring example with start index only

Now we will use only start index in the substring method. This should return the remaining string after the start value. See example by clicking the link below:

Experience this example online

We given the starting index 5 and remaining substring returned as “is javascript string tutorial!”.

JavaScript string substring example with greater end index

As mentioned earlier, when given end index in substring method is greater than the start index then the order will be inverted, i.e. end index becomes starting index while start value becomes end index.

Experience this example online

As you can see the index numbers are given as str.substring(18,5) in the JavaScript substring method. While the alert is showing returned string as this: str.substring(5,18).

A substring with negative number example

If a negative number is given in the substring method then it will be taken as zero.  Following example uses -10 for start index:

Experience this example online

The returned substring is started from beginning to 14 characters.