substr() Vs. substring()

In JavaScript, both the substr() and substring() methods are used to extract substrings from a given string. However, they differ in how they operate and handle certain scenarios:

substr() Method

The substr() method extracts a portion of a string based on the starting index and a specified length. The parameters are the starting index and the number of characters to extract.

const originalString = "Hello, World!"; const extractedSubstring = originalString.substr(7, 5); // Extracts "World"

If the length parameter is omitted, the method extracts characters from the starting index to the end of the string.

substring() Method

The substring() method also extracts a portion of a string, but it uses two indices as parameters: the starting index and the ending index (exclusive). It always extracts characters between the two indices.

const originalString = "Hello, World!"; const extractedSubstring = originalString.substring(7, 12); // Extracts "World"

If the starting index is greater than the ending index, substring() swaps the indices, ensuring that the substring is extracted correctly.

substr() Vs. substring() | Javascript

  1. substr() uses the starting index and length as parameters, while substring() uses the starting and ending indices.
  2. Negative indices in substr() count from the end of the string, whereas in substring(), negative indices are treated as 0.
  3. If the length parameter in substr() is negative, it's treated as 0. In substring(), if either index is negative or greater than the string length, they are treated as 0.
Examples:
const exampleString = "This is an example string"; const substrResult = exampleString.substr(5, 7); // Result: "is an e" const substringResult = exampleString.substring(5, 12); // Result: "is an e" const substrNegative = exampleString.substr(-9); // Result: "example string" const substringNegative = exampleString.substring(-9); // Result: "This is an example string"

Conclusion

While both methods are used to extract substrings, substr() uses the starting index and length, while substring() uses the starting and ending indices. The choice between them depends on your specific requirements for substring extraction.