Using String substr() method to coding in Javascript/JS

This JavaScript tutorial explains how to use the string approach referred to as substr() with syntax and examples.


In JavaScript, substr() is a string technique that is used to extract a substring from a string, given a begin function and a length. Because the substr() method is a technique of the String object, it ought to be invoked thru a specific occasion of the String class.

WARNING: It is encouraged that you use the substring() method instead, if possible. The substr() method is a legacy function.


In JavaScript, the syntax for the substr() method is:

string.substr(start_position [, length]);

Parameters or Arguments

start_position The function in string the place the extraction will start. The first function in string is zero If a poor fee is furnished for this parameter, the substr() method will measure the role from the cease of the string. For example, a value of -1 is the last character in the string, a price of -2 is the second ultimate personality in the string and so on. length Optional. It is the quantity of characters to extract from string. If this parameter is no longer provided, the substr() technique will extract to the cease of the string.


The substr() technique returns a substring that has been extracted from string given the start_position and length to extract.


The substr() technique does now not change the fee of the authentic string. See additionally the slice() and the substring() methods.


Let’s take a appear at an instance of how to use the substr() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet';


In this example, we have declared a variable known as totn_string that is assigned the string price of ‘TechOnTheNet’. We have then invoked the substr() approach of the totn_string variable to extract the substring from the string.

We have written the output of the substr() method to the internet browser console log, for demonstration purposes, to show what the substr() technique returns.

The following will be output to the web browser console log:


As you can see, the substr() technique returned ‘Tech’ for the first call, ‘On’ for the second call, ‘The’ for the 1/3 name and ‘Net’ for the fourth call.

Specifying a Negative Start Position

You can also use a negative start_position to extract a substring the use of the substr() method. A bad start_position lets in you to determine a role relative to the quit of the string when extracting the substring.

For example:

var totn_string = 'TechOnTheNet';


The following will be output to the web browser console log:


In this example, we have set the start_position parameter to a fee of -3 and we have not furnished a length parameter. This potential that the substr() approach will extract the substring beginning at the 0.33 closing personality until the stop of the string (allowing us to extract the ultimate 3 characters of the string).