what's the difference between javascript substr and substring?


What's the difference between the javascript substr and substring, which is better to use and when?

console.log("testing".substr(0,3));

console.log("testing".substring(0,3));
//tes

Both gives same results


Asked by:- jaiprakash
0
: 351 At:- 3/6/2018 1:38:31 PM
javascript javascript substring javascript substr






2 Answers
profileImage Answered by:- bhanu

When using substr() the first parameter is the starting index but the second parameter is the length of the substring: 

var s = "string";
s.substr(1, 3); // would return 'tri'

var s = "another example";
s.substr(3, 7); // would return 'ther ex'

When using substring() it is used to take a part of a string. Syntax is substring(first_index,last_index). So for instance

var a = 'Hello world!';
document.write(a.substring(4,8));

gives 'o wo', from the first 'o' (index 4) to the second one (index 7) Note that the 'r' (index 8) is not part of this substring.

You can also do

var a = 'Hello world!';
document.write(a.substring(4));

This gives the whole string from the character with index 4 on: 'o world!'

2
At:- 3/7/2018 7:35:51 AM
thanks 0
By : jaiprakash - at :- 3/8/2018 6:03:16 PM


profileImage Answered by:- neena

Main difference between substring and substr JavaScript method are in there second parameter, substring accept index of last character + 1, while substr() method gets expected length of substring.

Both substr(to, length) and substring(to, from) both takes two parameters, but substr takes length of substring to be returned, while substring takes end index (excluding) for substring.

Consider the below example:

var stringVar = "substr_vs_substring";
stringVar.substr(start, length);
stringVar.substring(start, stop);
stringVar.substring(1 , 4) 
// return "ubs";
stringVar.substr(1 , 4)
// returns "ubst";
1
At:- 3/7/2018 8:15:56 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly