InterviewHubPRO
Section Overview
Q474

Question 474 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

91%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

What is the difference between substring and substr methods?

Both substring and substr are used to extract parts of a string, but there are subtle differences between the substring() and substr() methods in terms of syntax and behavior.

  1. substring(start, end)
    • Parameters:
      • start: The index to start extracting (inclusive).
      • end: The index to stop extracting (exclusive).
    • Behavior:
      • If start > end, it swaps the arguments.
      • Negative values are treated as 0.
javascript
      let str = "Hello World";
      console.log(str.substring(0, 5));   // "Hello"
      console.log(str.substring(5, 0));   // "Hello" (swapped)
      console.log(str.substring(-3, 4));  // "Hell" (negative = 0)
  1. substr(start, length) (Deprecated)

    • Parameters:
      • start: The index to start extracting.
      • length: The number of characters to extract.
    • Behavior:
      • If start is negative, it counts from the end of the string.
      • If length is omitted, it extracts to the end of the string.
javascript
     let str = "Hello World"; console.log(str.substr(0, 5)); // "Hello" 
     console.log(str.substr(-5, 3)); // "Wor" (starts from 'W')`
vbnet
 **Note:** substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.