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
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!'
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";
substr
takes parameters as (from, length) while substring
takes parameters as (from, to).
example
alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"
substr() is a deprecated method
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly