substr vs substring in Javascript

By Avinash

January 17, 2012Web Development2 Comments

We have these two functions to get the part of the string in JavaScript. But both have slight different usage over each other. We can use any one based on our need. I am going explain the major difference between these two functions.

Both the function extract the part of the string from the given string. So I will concentrate on difference rather than full detailed explanation of these functions.

Both the functions have same number of parameters (two), but the parameter which makes them behave different than each other is the second parameter. Have a look at more details on this.

substr() in JavaScript

First Parameter indicates the starting point and second parameter indicates length of the string you want to generate.

So if you want to get the substring which start from second character and have a length of 5 character the below code with be used.

var main_string = "Hi Expert Developer"; var sub_string = main_string.substr(1,5); console.log(sub_string); // will log // "i Exp"
  var main_string = "Hi Expert Developer";
  var sub_string = main_string.substr(1,5);
  console.log(sub_string);
  // will log
  // "i Exp"

substring() in JavaScript

Like substr first parameter in substring indicates the starting index but second parameter indicates the ending index of the string.

So if you want to get the string from main string which start from second character and end at fifth char, below code will be used.

var main_string = "Hi Expert Developer"; var sub_string = main_string.substring(1,5); console.log(sub_string); // will log // "i Ex"
  var main_string = "Hi Expert Developer";
  var sub_string = main_string.substring(1,5);
  console.log(sub_string);
  // will log
  // "i Ex"

Now lets apply same parameter on both functions and check the output from the same string.

var main_string = "Hi Expert Developer"; var sub_string1 = main_string.substr(4,8); var sub_string2 = main_string.substring(4,8); // "xpert De" console.log(sub_string1); // "xper" console.log(sub_string2);
  var main_string = "Hi Expert Developer";
  var sub_string1 = main_string.substr(4,8);
  var sub_string2 = main_string.substring(4,8);
 
  // "xpert De"
  console.log(sub_string1);
 
  // "xper"
  console.log(sub_string2);

Hope you are clear with difference in these two functions. So you would have better idea for which one to use.

Share your thoughts on this via comments.

Share This Article