Substring vs Substr In Javascript

In JavaScript, the substring() method and substr() method are often compared due to their similarities in functionality. Let’s compare the two methods:

  1. Parameters: The substring() method takes two parameters: the starting index and the ending index. It extracts the characters from the starting index up to, but not including, the ending index. If the starting index is greater than the ending index, the method swaps the values internally to ensure correct extraction.The substr() method, on the other hand, also takes two parameters: the starting index and the length of the substring to extract. It extracts a substring starting from the given index and spanning the specified length.
  2. Negative Parameters: Both methods handle negative parameters differently. In substring(), negative parameters are treated as 0, meaning they start from the beginning of the string. In contrast, substr() interprets a negative starting index as counting from the end of the string.
  3. Compatibility: Both substring() and substr() are widely supported in modern JavaScript environments, including all major browsers. However, substring() is considered more standard and has been around since the early versions of JavaScript, while substr() was introduced in ECMAScript 3.

Here are examples showcasing the differences between the two methods:

Example 1:

var str = "Hello, World!";
var substring = str.substring(0, 5);
var substr = str.substr(0, 5);

console.log(substring); // Output: Hello
console.log(substr);    // Output: Hello

In this example, both substring() and substr() are used to extract the same substring, “Hello”, from the str string. The results are identical because the starting index and length are the same.

Example 2:

var str = "JavaScript is awesome!";
var substring = str.substring(4, 10);
var substr = str.substr(4, 10);

console.log(substring); // Output: Script
console.log(substr);    // Output: Script is 

Here, both methods are used to extract substrings starting from index 4. However, the difference becomes apparent in the second parameter. substring() specifies the ending index, while substr() specifies the length of the substring. As a result, substring(4, 10) extracts “Script”, while substr(4, 10) extracts “Script is “.

In summary, substring() and substr() have similar functionalities for extracting substrings, but their parameter handling and behavior differ slightly. It’s important to understand these differences to use the appropriate method based on your specific requirements.