substr vs. substring in JavaScript

July 8, 2016

The difference between substr vs. substring in JavaScript bites me more often than any other API confusion in the language. The only difference is in the second parameter. Do you know what each of these will return?

var word = "The quick brown fox";
console.log(word.substr(5, 10));
console.log(word.substring(5, 10));

substr vs. substring

String.prototype.substr() and String.prototype.substring() have identical looking APIs in that they both take two parameters and the first parameter for both methods is the numerical index of the string we’re going to be doing substitutions on. The second parameter is where they differ.

Substring’s second parameter is the numerical index on which you stop the substitution; substr’s second parameter is the length of the substitution.

So, to review the code from above:

var word = "The quick brown fox";

// Cut from the 5th character, 10 characters long
console.log(word.substr(5, 10)); // returns "uick brown"

// Cut from the 5th character to the 10th character
console.log(word.substring(5, 10)); // returns "uick "

I hope that helps!