Skip to content

Commit 4308b86

Browse files
doc: update question 467 substr vs substring
1 parent a5cf154 commit 4308b86

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

README.md

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8845,8 +8845,29 @@ The execution context is created when a function is called. The function's code
88458845
**[⬆ Back to Top](#table-of-contents)**
88468846
88478847
467. ### What is the difference between substring and substr methods?
8848-
Both substring() and substr() are string methods, which are used to find substring of a given string. But there are some notable differences with their usage,
8849-
8848+
There are subtle differences between the substring() and substr() methods, so you should be careful not to get them confused.
8849+
8850+
- The two parameters of substr() are start and length, while for substring(), they are start and end.
8851+
- substr()'s start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0.
8852+
- Negative lengths in substr() are treated as zero, while substring() will swap the two indexes if end is less than start.
8853+
8854+
Furthermore, substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.
8855+
8856+
```javascript
8857+
const text = "Mozilla";
8858+
console.log(text.substring(2, 5)); // "zil"
8859+
console.log(text.substr(2, 3)); // "zil"
8860+
```
8861+
8862+
sources:
8863+
- [substring mdn web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring#the_difference_between_substring_and_substr)
8864+
- [substr mdn web docs (deprecated)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
8865+
- [substr current ecmascript specification](https://262.ecma-international.org/14.0/index.html?_gl=1*1bpcj45*_ga*NDgyMjM0MDA0LjE3MjY2MDQ1OTM.*_ga_TDCK4DWEPP*MTcyNjYwNDU5My4xLjEuMTcyNjYwNDc0OS4wLjAuMA..#sec-string.prototype.substr)
8866+
- [substr draft ecmascript specification](https://tc39.es/ecma262/#sec-string.prototype.substr)
8867+
- [substring current ecmascript specification](https://262.ecma-international.org/14.0/index.html?_gl=1*1bpcj45*_ga*NDgyMjM0MDA0LjE3MjY2MDQ1OTM.*_ga_TDCK4DWEPP*MTcyNjYwNDU5My4xLjEuMTcyNjYwNDc0OS4wLjAuMA..#sec-string.prototype.substring)
8868+
- [substring draft ecmascript specification](https://tc39.es/ecma262/#sec-string.prototype.substring)
8869+
- [substr caniuse](https://caniuse.com/mdn-javascript_builtins_string_substr)
8870+
- [substring caniuse](https://caniuse.com/mdn-javascript_builtins_string_substring)
88508871
88518872
**[⬆ Back to Top](#table-of-contents)**
88528873

0 commit comments

Comments
 (0)