Skip to content

Substring vs Substr in JavaScript

In JavaScript, substring() and substr() functions are used to get the specified part of the string but there’s a small difference between substring and substr methods in JavaScript.

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.

String.prototype.substring()

The substring() method returns a part of the string between the start and end index, or to the end of the string, depending on the parameters that you pass.

Syntax

str.substring(startIndex[, endIndex])

endIndex is optional. It’s the index value of the first character to exclude from the returned substring.

Examples

var str = 'Poopcode';

console.log(str.substring(0, 1));
console.log(str.substring(1, 0));
//P

console.log(str.substring(0, 6));
//Poopco

console.log(str.substring(4));
console.log(str.substring(4, 8));
console.log(str.substring(8, 4));
//code


console.log(str.substring(0, 8));
console.log(str.substring(0, 10));
//Poopcode



//Length can also be used with substring
console.log(str.substring(str.length - 4));
//code

String.prototype.substr()

The substr() method returns a part of the string, starting at the specified index and extending for a given number of characters afterwards.

The substr() method is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future.

Syntax

str.substr(start[, length])

length is optional number of characters to extract.

Notes

  • If start is a positive number, the index starts from the start of the string.
  • If start is a negative number, the index starts from the end of the string.
  • If length is omitted, substr() extracts characters to the end of the string.
  • If length is undefined, substr() extracts characters to the end of the string.
  • If length is a negative number, it is treated as 0.
  • For both start and length, NaN is treated as 0.

Examples

var str = 'Poopcode';

console.log(str.substr(0, 1));   // 'P'
console.log(str.substr(1, 0));   // ''
console.log(str.substr(-1, 1));  // 'e'
console.log(str.substr(1, -1));  // ''
console.log(str.substr(-3));     // 'ode'
console.log(str.substr(1));      // 'oopcode'
console.log(str.substr(-20, 2)); // 'Po'
console.log(str.substr(20, 2));  // ''

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.