JavaScript question detail
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.
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.
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)
substr(start, length)(Deprecated)
- Parameters:
start: The index to start extracting.length: The number of characters to extract.- Behavior:
- If
startis negative, it counts from the end of the string. - If
lengthis omitted, it extracts to the end of the string.
let str = "Hello World"; console.log(str.substr(0, 5)); // "Hello"
console.log(str.substr(-5, 3)); // "Wor" (starts from 'W')`
Note: substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.