JavaScript String substring() Tutorial

In this section, we will learn what the substring() method is and how to use it in JavaScript.

JavaScript String substring() Method

The `substring()` method is used to extract a sub-string from a text value.

Note: this method won’t change the original string value.

JavaScript String substring() Syntax

string.substring(start, end)

String substring() Method Parameters:

The method takes two arguments:

  • The first argument is the index number from which the extraction should begin.

Notes:

If the value is a negative number, it’ll be converted into 0.

The first character in a string value starts from the index number 0.

  • The second number declares the end index of the extraction.

Note: again, if the value here is negative, it will be converted into 0.

Also, if the first argument is a value that is greater than the second argument, the execution engine will automatically change the position of the two arguments.

Example:

substring(5, -4);

Will become:

substring(0,5);

Note: remember a negative number automatically is converted into the value 0.

String substring() Method Return Value:

The return value of this method is an extracted sub-string from the target string value.

Example: get substring in JavaScript

console.log("This is for test".substring(-4,4));

Output:

This

Example: using substring() method in JavaScript

console.log("This is for test".substring(4,0));

Note that in this example, the second argument is lower than the first argument! So JavaScript Execution Engine automatically changed their position and basically behind the scene this became the actual arguments:

substring(0,4);

Leave a Reply