Skip to content
the poor coder

JavaScript substr()

Poor Man
Published
Reading time
1 min read
On this page

JavaScript substr()#

The substr() method in JavaScript is used to extract a part of a string, starting from a specified position and for a specified length of characters. It can be used to retrieve a substring from the original string.

Syntax:#

Text
string.substr(start, length)
  • start: Required. The position where to start the extraction from. A positive number represents the index of the character to start from, while a negative number represents the position from the end of the string. For example, -1 represents the last character of the string.
  • length: Optional. The number of characters to extract. If omitted, all characters from the start position to the end of the string will be extracted.

Examples:#

Let's say we have a string "Hello, World!":

Text
const str = "Hello, World!";

To extract the first 5 characters from the string, we can use:

Text
const substr1 = str.substr(0, 5);

The value of substr1 will be "Hello".

To extract the last 6 characters from the string, we can use:

Text
const substr2 = str.substr(-6);

The value of substr2 will be "World!".

Multiple ways to achieve the same result:#

  • We can also use the slice() method to achieve the same result. The syntax is similar to substr(), except that slice() uses the end position instead of the length.
  • We can also use string indexing to extract substrings. For example, str[0] will give us the first character of the string, and str[2] will give us the third character of the string.

Overall, the substr() method is a useful way to extract substrings from a larger string in JavaScript.

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