Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

What is substr() in JavaScript?

Mahnoor Zaheer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
The syntax of the substring() method in JavaScript

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)
The code example of substr() in JavaScript

RELATED TAGS

javascript
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring