0

What is the difference between .substr and .substring in javascript?

7th Oct 2017, 7:19 PM
Vitaliy Angelov (Rostov-on-Don)
Vitaliy Angelov (Rostov-on-Don) - avatar
2 Answers
+ 8
The difference is in the second argument. The second argument tosubstringĀ is the index to stop at (but not include), but the second argument toĀ substrĀ is the maximum length to return. You can rememberĀ substringtakes indices, as does yet another string extraction method, slice. Links? https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring //I got this from Stack Overflow Javascript has two string methods (substrĀ andĀ substring) that appear to be identical at first glance; they both return a substring from a given string. So what's the difference? Their second parameters, while both numbers, are expecting two different things. When usingĀ substringĀ the second parameter is the first index not to include: var s = "string"; s.substring(1, 3); // would return 'tr' var s = "another example"; s.substring(3, 7); // would return 'ther' When usingĀ substrĀ the second parameter is the number of characters to include in the substring: var s = "string"; s.substr(1, 3); // would return 'tri' var s = "another example"; s.substr(3, 7); // would return 'ther ex' //got this from Nathan Hoad
7th Oct 2017, 10:56 PM
Koketso Dithipe
Koketso Dithipe - avatar
+ 1
@vitaliy angelov are you using any social media
23rd Oct 2017, 5:56 PM
Raj Chhatrala
Raj Chhatrala - avatar