Substring vs Substr Javascript

substring vs substr javascript

Similar to how the difference between the slice vs splice array methods can be hard to remember, it can also be hard to remember the difference between the substring vs substr JavaScript string methods. Here’s a quick reference to help out with that.

String.prototype.substring – subtring vs substr javascript

The substring() method, all spelled out, returns a new string with a subset of the string. With one argument passed-in, we get the string starting from the specified index (inclusive) until the end of the string:

With two arguments passed-in, we get a subset of the string from the starting index to the end index (exclusive):

String.prototype.substr  – subtring vs substr javascript

The substr() method is very similar, but the second argument is not for the end index, it’s for the amount of characters.

Here we want a 3-character string from a starting index of 2:

Negative start index – subtring vs substr javascript

Additionally, the first argument to substr can be a negative integer, in which case the start of the returned string is counted from the end of the string that the method is used on:

Same Result When Only One Argument – subtring vs substr javascript

When only the first argument is used and is a positive integer, both substring and substr return the same value:

Yes that is difference of subtring vs substr javascript. you can read anther post in here