What is JavaScript substr method?

The substr method is used to get the substring of a given string. The substr method takes two arguments; one is the starting position and the other specifies the length of the returned substring.

The Javascript substr method is different to the substring method in that you can specify end index in the substring method. Whereas the second parameter in JS substr is the length parameter.

See an example of substr

How to use the substr method?

Following is the syntax to use the substr method:

Str.substr(start_index, length);

A few points about substr method are:

  • The start_index specifies where to start extracting the substring.
  • The Length specifies the returned string’s length, starting from start_index number
  • If the length parameter is not provided then the substr method will return the remaining string (to the end).
  • The original string remains the same after using substr JavaScript method.
  • If you use a negative number in the substr method it will start counting from the end of the string.

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

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

substr with start index and length parameters demo

Following example uses both arguments in the substr method. We will specify the start index and the length of the returned string. Click the link or image below to see the demo online:

Experience this example online

As you can see, we specified start index as 8 and length to be returned is 17 characters. The substr function returned “javascript tutorial” substring from the original string: “This is javascript string tutorial!”

Substr example with the start index only

In this example, we will only specify the start index. No length is given and it should return the remaining string. See the example online by clicking the link below:

Experience this example online

As you can see, we specified 8 as starting index and did not specify the length argument. The alert shows the remaining string as:

“javascript string tutorial!”

The substr with negative index example

If you specify a negative number in starting index of the JavaScript substr method, it will be counted from the end of given string. See example below:

Experience this example online

We specified -10 and the returned string is “tutorial!”. So characters started counting from ‘!’ which is the last character of the string as we specified a negative number in the substr method.

Further Reading: JavaScript String | Javascript substring