JavaScript substr()

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:

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!":

const str = "Hello, World!";

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

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:

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.

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