JavaScript SubStr

The JavaScript SubStr or substring function is one of the String functions, which is used to extract the part of a string and return in a new string. The syntax of the JavaScript SubStr() function to return substring is:

String_Object.substr(Start, Length)

JavaScript Substring function will accept two arguments. The first integer value is the index position where the extraction will start, and the second integer value is the length of the substring.

JavaScript Substring Function Example

The following set of examples will help you understand the SubStr function in JavaScript Programming Language.

<!DOCTYPE html>
    <title> SubStr JavaScript </title>
    <h1> JavaScript SubStr </h1>
    var Str1 = "Tutorial Gateway";
    var Str2 = Str1.substr(2, 8);
    var Str3 = Str1.substr(0, 8);
    var Str4 = Str1.substr(2);
    var Str5 = Str1.substr(2, -3);
    var Str6 = Str1.substr(2, 0);
    var Str7 = Str1.substr(-3);
    var Str8 = Str1.substr(-3, 2);
    document.write(Str2 + "<br \>");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
    document.write(Str6 + "<br \>");
    document.write(Str7 + "<br \>");
    document.write(Str8 );
JavaScript SUBSTR Function

The following statement will extract five characters from the original string, starting at index position 2

var Str2 = Str1.substr(2, 8);

Next, We omitted the second argument. It means JavaScript substring function will start at index position two and ends when it reaches last.

var Str4 = Str1.substr(2);

Within the following JavaScript statements, we used Negative and Zero values as the second argument. As we said before, this will return an empty string

  var Str5 = Str1.substr(2, -3);
  var Str6 = Str1.substr(2, 0);

Next, we used negative indexing. The following statement starts extracting from -3 (index position of 3 from right to left) and ends at last position.

var Str7 = Str1.substr(-3);

HINT: If you are using the Negative numbers as index, JavaScript will start looking for items from right to left (Here, -1 is the Last Item, -2 is Last but one etc)