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
1
: 3069 At:- 3/6/2018 1:38:31 PM
javascript javascript substring javascript substr







3 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!'

3
At:- 3/7/2018 7:35:51 AM Updated at:- 12/24/2022 8:55:22 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


profileImage Answered by:- jon

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.

0
At:- 6/23/2022 7:21:08 AM Updated at:- 12/24/2022 3:06:33 PM






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