Skip to content
the poor coder

substr() javascript

Poor Man
Published
Reading time
2 min read
On this page

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:#

Text

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:

Text

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC