DEV Community

oest0004
oest0004

Posted on

string.prototype.substring() vs string.prototype.substr()

Introduction

The string.prototype.substr() method and the newer string.protoype.substring() method, at first glance, accomplish the same thing: for a given string, return a smaller sub-string from some position within the string. there are, however, subtle differences between the two methods, which I will detail below. But first, let's review the parameters of the two methods:

The string.prototype.substr() Method

The string.prototype.substr takes two parameters, start and length in the order substr(start,length). Both parameters expect non-negative numbers.

The method returns a string starting at index start of the object string and of length length. If length is omitted or undefined, it will return characters to the end of the string.

if start is a negative number, the index starts counting from the end of the string, but the length parameter still makes it count towards the end of the string

Example

let word = "Apple Pie"

let substr1 = word.substr(1,4) // 'pple'
let substr2 = word.substr(6) // 'Pie'
let substr3 = word.substr(-3,2) // 'Pi'
let substr4 = word.substr(-9,5) // 'Apple'
Enter fullscreen mode Exit fullscreen mode

The string.prototype.substr() method is the older of the two methods, and is currently marked as [deprecated]https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring. While it remains functional, it is recommended to use the string.prototype.substring() method instead, as it could be removed from future versions of ECMAScript.

The string.prototype.substring() Method

The string.prototype.substring() takes two parameters, indexStart and indexEnd in the order substring(indexStart,indexEnd). Both parameters are numbers. For a given string object, it returns characters from index specified in indexStart up to but not including the character at index indexEnd

If indexStart is omitted, it will return characters to the end of the string. If indexStart is larger than indexEnd, the method will reverse the two values, such that the larger of the two arguments is passed as indexEnd and the smaller of the two is passed as indexEnd. Any argument that is negative is treated as 0, while any argument that is larger than the length of the string object is treated as the length of the string object.

Example

let word = "Apple Pie"

let substring1 = word.substring(1,4) // 'ppl'
let substring2 = word.substring(6) // 'Pie'
let substring3 = word.substring(-3,2) // 'Ap'
let substring4 = word.substring(4,1) // 'ppl'
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
mang0088 profile image
Nikunj

Great post.
Overall, the arguments of substring() represent the starting and ending indexes, while the arguments of substr() represent the starting index and the number of characters to include in the returned string.