substr() javascript

What is substr() in JavaScript?

The substr() method in JavaScript is used to extract a portion of a string, starting from a specified index and then returns the extracted part.

Syntax:


string.substr(start, length)
  • start: Required. The starting index position of the substring. If it's negative, then it starts from the end of the string.
  • length: Optional. The number of characters that are going to be extracted from the given start position. If it's not given, then it extracts all the characters available from the start position.

Example:

Let's say we have a string "Hello World", and we want to extract the substring "World" from it. We can use the substr() method for this as shown below:


var str = "Hello World";
var result = str.substr(6, 5);
console.log(result); // Output: World

In the above example, we have passed two arguments to the substr() method. The first one is the starting index position (6), which is the "W" in "World". The second one is the length (5), which is the number of characters we want to extract from the starting position.

If we don't pass the second argument, then it extracts all the characters available from the given start position as shown below:


var str = "Hello World";
var result = str.substr(6);
console.log(result); // Output: World

In the above example, we have only passed the starting index position, and it has extracted all the characters available from that position till the end of the string.

There is another way to achieve the same result using the slice() method as shown below:


var str = "Hello World";
var result = str.slice(6, 11);
console.log(result); // Output: World

In the above example, we have used the slice() method instead of the substr() method to extract the same substring "World". The slice() method is also used to extract a portion of a string, but it takes the start and end positions as arguments instead of start and length.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe