javascript substr method

The substr method

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

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

See an example of substr

Syntax of javascript substr

Following is the syntax to use 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, started from start_index number
  • If length is not provided then the substr method will return remaining string (to the end).
  • The original string remains the same after using substr javascript method.
  • If you use a negative number in 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 in javascript.

substr with start index and length parameters example

Following example uses both arguments in the substr method. We will specify start index and length of returned string. Click the link below to see 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 original string: “This is javascript string tutorial!”

Substr example with the start index only

In this example, we will only specify start index. No length is given and it should return 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 remaining string as “javascript string tutorial!”.

substr with negative index example

If you specify a negative number in starting index of 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 ‘!’ last character of the string as we specified a negative number in javascript substr method..

Also see Javascript String | Javascript substring

Was this article helpful?

Related Articles

Leave A Comment?