substring() vs substr() in JavaScript: Key Differences
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
substring(start, end) and substr(start, length) both extract part of a string without changing the original. substring() uses a start index and an exclusive end index. If start is greater than end, JavaScript swaps them, and negative or NaN values become 0. For example, 'JavaScript'.substring(4, 0) returns 'Java'. substr() uses a start index and a length. A negative start counts from the end of the string, while a negative length returns an empty string. For example, 'JavaScript'.substr(-6, 6) returns 'Script'. If the end or length is omitted, extraction continues to the end. This makes substring() handy for bounded slices, while substr() can be confusing because its second argument is a length. Both return a new string, and out-of-range indexes are clamped to valid bounds. The code below logs outputs for common and edge cases. Inputs are numeric indexes or lengths; outputs are strings. Extraction takes O(k) time, where k is the length of the returned string, and O(k) space for the result; the original string remains unchanged. Prefer substring() or slice() for modern code: use substring() when you know the end index, and use slice() when you need negative indexes and consistent behavior.