Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between substr and substring?

What is the difference between

alert("abc".substr(0,2)); 

and

alert("abc".substring(0,2)); 

They both seem to output “ab”.

like image 633
Difference Engine Avatar asked Sep 19 '10 11:09

Difference Engine


People also ask

What is difference between substr and substring in SQL?

substring is the sql operation defined in the sql standard ISE:IEC 9075:1992. substr is an old syntax used by oracle. This wrong syntax is completely inconsistent with sql usage of real english words, never abbreviations. Oracle still does not support the standard syntax.

What is difference between slice () substring () and substr ()?

slice() extracts parts of a string and returns the extracted parts in a new string. substr() extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. substring() extracts parts of a string and returns the extracted parts in a new string.

What is difference between string and substring?

a substring is a subsequence of a string in which the characters must be drawn from contiguous positions in the string. For example the string CATCGA, the subsequence ATCG is a substring but the subsequence CTCA is not.

What's the difference between Slice and substring?

A big difference with substring() is that if the 1st argument is greater than the 2nd argument, substring() will swap them. slice() returns an empty string if the 1st argument is greater than the 2nd argument.


2 Answers

The difference is in the second argument. The second argument to substring is the index to stop at (but not include), but the second argument to substr is the maximum length to return.

Links?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring

like image 185
Delan Azabani Avatar answered Oct 17 '22 22:10

Delan Azabani


substr (MDN) takes parameters as (from, length).
substring (MDN) takes parameters as (from, to).

Update: MDN considers substr legacy.

alert("abc".substr(1,2)); // returns "bc" alert("abc".substring(1,2)); // returns "b" 

You can remember substring (with an i) takes indices, as does yet another string extraction method, slice (with an i).

When starting from 0 you can use either method.

like image 21
Colin Hebert Avatar answered Oct 17 '22 22:10

Colin Hebert