What is substr() in JavaScript?

The substr() method in JavaScript returns a part of a string from the specified index without changing the original string.

Syntax

The syntax of this method is as follows:

string.substr(startIndex, length)

Parameters

The substr() method takes two parameters, one mandatory and one optional.

  • startIndex (required): The integer value of the starting index, i.e., where the substring extraction should start.
  • length (optional): The integer value of the length of the substring that needs to be extracted. If length is not specified, the string is extracted until the end.

Return value

The return value is a string that is a part of the original string.

Code

In the first example below, the substring is extracted without specifying its length, and so the complete string starting from the specified index is taken out.

In the second example, when the length of the substring is specified, the function extracts the part starting from the given index until the required length is achieved.

// Example no.1
// extracting a substring without specifying length
let str = "Welcome to Educative";
let x = str.substr(4);
console.log(x)
// Example no.2
// extracting a substring by specifying length
let y = str.substr(11,3);
console.log(y)

Free Resources