1

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.

If starting at the first character in a string, is there any preference to using substr(0,n) over substring(0,n)?

user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

2

The only real difference between the two is that substr() is non-standard1, while substring() are standard built-in functions, ignoring differences when the starting index is not 0.

slice() is also very similar, but allows negative end indices (number from end, which substring() does not allow).

1:substr() is not officially standard, though pretty much all browsers support it. For compatibility reasons, the standardising committee provides a "recommended" way of implementing this non-standard function, but it's not part of the official standard.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
  • Thanks, I didn't know that substr() was non-standard. How does one know what is standard versus non-standard? – user1032531 Oct 16 '13 at 12:32
  • @user1032531: it's _almost_ standard, but not officially so (though pretty much all browsers support it). For compatibility reasons, the standardising committee provides a "recommended" way of implementing this non-standard function, but it's not part of the official JavaScript standard. You can find out by reading [the ECMAScript Specification](http://ecma-international.org/ecma-262/5.1/) (yes, big mouthful) - that's the official standard for the JavaScript language. – Qantas 94 Heavy Oct 16 '13 at 12:33
  • Thanks again. I looked at the spec. Quite a document. I will take your word for which one is the standard! – user1032531 Oct 16 '13 at 12:38
  • @user1032531: another resource, a bit less of a mouthful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr It says that it's never been in, but there is a section saying how it would be "nice" to do it. – Qantas 94 Heavy Oct 16 '13 at 12:39