menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:substr() method

menu

The substr() method in JavaScript is used to extract a substring from a string. It's similar to the substring() method, but it has a slightly different behavior. The substr() method takes two arguments: the start index and the length of the substring. Here's a deep dive into the substr() method in JavaScript:

Syntax:

javascriptstring.substr(start);
string.substr(start, length);
  • string: The string from which you want to extract a substring.

  • start: The index at which the extraction begins. If negative, it counts from the end of the string.

  • length (optional): The length of the substring to extract. If omitted, it extracts from the start index to the end of the string.

Basic Example:

javascriptconst text = "Hello, World!";
const subText = text.substr(7, 5);
console.log(subText); // "World"

In this example, the substr() method extracts a substring of length 5 starting at index 7 from the text string, resulting in the string "World."

Using Negative Indices:

Negative indices are handled differently in the substr() method compared to substring(). If the start index is negative, it counts from the end of the string, while the length parameter can be negative to count characters from the end of the string:

javascriptconst text = "Hello, World!";
const subText = text.substr(-6, 3);
console.log(subText); // "Wor"

Here, the start index -6 counts from the end of the string, and the length 3 determines the number of characters to extract.

Omitted Length:

When you omit the length parameter, the substr() method extracts characters from the start index to the end of the string:

javascriptconst text = "Hello, World!";
const subText = text.substr(7);
console.log(subText); // "World!"

The substr() method starts at index 7 and extracts characters until the end of the text string.

Returning a New String:

The substr() method returns a new string containing the extracted characters. It does not modify the original string.

Non-Mutating and Immutability:

substr() is a non-mutating method, meaning it doesn't change the original string. It is suitable for working with immutable data structures.

Use Cases:

  • Extracting substrings of a specific length from a larger string.

  • Trimming or extracting fixed-length portions of text.

  • Creating a copy of a string without modifying the original.

The substr() method is a versatile tool for working with substrings in JavaScript. It is commonly used in text manipulation, string manipulation, and various other scenarios where you need to extract specific-length portions of a string.

1280 x 720 px