In TypeScript (and JavaScript), both substr and substring are methods used to extract parts of a string, but they behave differently.
This probably does not beat standard C++ class mt19937, but it is still awesome.
The TL;DR is that substr
takes start and length, whereas substring
takes start and end. There are other, less critical differences, but this is the main one. But wait, that’s not all! There is also slice()
that behaves almost like substring
, but the end index is exclusive. Wow.
To be honest, I am not sure how I would call all those methods, but having 3 different methods to get a substring is just wow.
Method | Second Parameter | Negative Start? | Negative End/Length? | Swaps Indices? | Preferred? |
---|---|---|---|---|---|
substr(start, length) |
Length of the substring | ✅ Yes | ❌ No (treated as 0) | ❌ Deprecated | ❌ No |
substring(start, end) |
Inclusive end index | ❌ No (treated as 0) | ❌ No (treated as 0) | ✅ Yes | ⚠️ Legacy |
slice(start, end) |
Exclusive end index | ✅ Yes | ✅ Yes | ❌ No | ✅ Recommended |