W3jar
310 words
2 minutes

Difference Between JavaScript substr() and substring()

In JavaScript, both substr() and substring() are methods used to extract portions of a string, but they have some differences in how they work. Here’s a breakdown of each method:

substr()#

  • Syntax: str.substr(start, length)

    • start: The starting index from which to begin extraction.
    • length: The number of characters to extract.
  • Behavior:

    • Extracts a substring starting from the start index and extracts characters up to the specified length.
    • If length is omitted, it extracts till the end of the string.
    • If start is negative, it is treated as an offset from the end of the string.
  • Example:

    let str = "Hello, world!";
    console.log(str.substr(7, 5)); // Outputs: "world"
    console.log(str.substr(-6, 5)); // Outputs: "world"
    

substring()#

  • Syntax: str.substring(indexStart, indexEnd)

    • indexStart: The index at which to start extraction.
    • indexEnd: The index at which to end extraction (not inclusive).
  • Behavior:

    • Extracts a substring starting from indexStart up to but not including indexEnd.
    • If indexEnd is omitted, it extracts till the end of the string.
    • If indexStart is greater than indexEnd, the method will swap them.
    • Does not handle negative indices.
  • Example:

    let str = "Hello, world!";
    console.log(str.substring(7, 12)); // Outputs: "world"
    console.log(str.substring(12, 7)); // Outputs: "world" (start and end are swapped)
    

Key Differences#

  1. Index Handling:

    • substr() can take a negative start value to count from the end of the string.
    • substring() does not support negative indices and will treat them as zero.
  2. Parameters:

    • substr() requires the length of the substring as its second parameter.
    • substring() requires the end index but not the length.
  3. Behavior with Reversed Indices:

    • substr() does not swap its parameters; it extracts from the start index to the length specified.
    • substring() swaps the parameters if the start index is greater than the end index.

Example Demonstrations:#

let str = "JavaScript";

// Using substr()
console.log(str.substr(4, 6)); // Outputs: "Script"
console.log(str.substr(-6, 6)); // Outputs: "Script"

// Using substring()
console.log(str.substring(4, 10)); // Outputs: "Script"
console.log(str.substring(10, 4)); // Outputs: "Script" (start and end are swapped)

In modern JavaScript, substr() is considered somewhat outdated and may be deprecated in future versions, with substring() or other methods like slice() being more commonly recommended.