Use str.slice(..)
There are three ways to get a substring from a string in JavaScript:
str.substr(startIndex,length)str.substring(startIndex,endIndexPlusOne)str.slice(startIndex,endIndexPlusOne)
substr and substring
All browsers treat str.substring(-2) as str.substring(0).
substring(4,2) inputs are automatically reversed when the second param is less than the first, resulting in substring(2,4). So substring(12,-2) is treated as substring(0,12).
IE treats str.substr(-2) as str.substr(0). All others support neg index in substr.
All browsers support str.slice(-2).
slice is the only method that properly handles negative indexes across all browsers. Here's a demo, run in your current browser.
Starting string: var str = "abcdefghijklmnopqrstuvwxyz"
| code | result | desired | correct? |
|---|
Note if you are viewing this in IE, str.substr(-12,5) results in "abcde", whereas in other browsers "opqrs".
So in conclusion, there are too many ways to skin the substring cat. substr has cross-browser compatibility issues and substring doesn't support negative indexes. slice is always safe, so just use slice.