JavaScript - The Difference Between String.prototype.substr and String.prototype.substring

JavaScript gives us a few options for substring functions. The first is String.prototype.substr. The second is String.prototype.substring. Both accomplish the same thing, but there is a nuance between the two fuctions.


The signature for this function is str.substr(start, [length]). The first argument, start specifies the index that you’d like to start splitting a string at. The second argument, length, is an optional argument that allows you to specify how much of the string you would like after the start index.

As an example, let’s say we want to split the string 'testing'. The function call 'testing'.substr(0,1) will start at the first index in the string and retrieve one character. This call will return t. If you asked for a length of two: 'testing'.substr(0,2) we would get 'te'.


The signature for this is str.substring(indexStart, [indexEnd]). The first argument, indexStart, specifies the index of the first character to include in your string. The second argument, indexEnd, is an optional argument that allows you to specify the index of the first character to not include in your string.

Let’s use our same test string for an example. The function call 'testing'.substring(0,3) will return 'tes'. Now comes the nuance – the function call 'testing'.substring(3,0) will also return 'tes'. String.prototype.substr works by starting at the given index and going forward. String.prototype.substring, by contrast, allows you specify a portion of the string you want by index – it does not matter if the second argument in less than the first argument because it just treats the arguments as boundaries to the substring that you want.

261 Words

2017-10-15 06:00 +0000