String.prototype.substring() | substring substr javascript
Thesubstring()andslice()[1]methodsarealmostidentical,butthereareacoupleofsubtledifferencesbetweenthetwo,especiallyinthewaynegativeargumentsaredealtwith.Thesubstring()methodswapsitstwoargumentsifindexStartisgreaterthanindexEnd,meaningthatastringisstillreturned.Theslice()[2]methodreturnsanemptystringifthisisthecase.consttext="Mozilla";console.log(text.substring(5,2));console.log(text.slice(5,2));IfeitherorbothoftheargumentsarenegativeorNaN,thesubstring()methodtreatsthemasiftheywere0.console.lo...
The substring() and slice()[1] methods are almost identical, but there are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.
The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The slice()[2] method returns an empty string if this is the case.
const text = "Mozilla"; console.log(text.substring(5, 2)); console.log(text.slice(5, 2));If either or both of the arguments are negative or NaN, the substring() method treats them as if they were 0.
console.log(text.substring(-5, 2)); console.log(text.substring(-5, -2));slice() also treats NaN arguments as 0, but when it is given negative values it counts backwards from the end of the string to find the indexes.
console.log(text.slice(-5, 2)); console.log(text.slice(-5, -2));See the slice()[3] page for more examples with negative numbers. ...