Sitemap

Member-only story

Returning a part of a string

2 min readJul 30, 2018

--

Press enter or click to view image in full size

In JavaScript we have three very similar methods of returning a part of a string. In this article we will look at the similarities and subtle differences among the three.

String.prototype.substr()

First method is substr, which obviously stands for substring. This method takes two arguments: indexStart and length. It extracts all characters, starting and including indexStart and number of characters as equal to length. The latter is optional and if omitted then the method will return all characters starting from indexStart to the end of the string.

Let’s see this on actual example:

const string = 'Medium';
console.log(string.substr(0,3)); // Returns: Med
console.log(string.substr(1,4)); // Returns: ediu
console.log(string.substr(2)); // Returns: dium

If we length is negative it will be treated as 0:

const string = 'Medium';
console.log(string.substr(1,-1)); // Returns: ""
console.log(string.substr(1,0)); // Returns: ""

If indexStart is negative, then the string will be extracted from the end (where -1 is the last character):

const string = 'Medium';
console.log(string.substr(-3)); // Returns: "ium"
console.log(string.substr(-3,2)); // Returns: "iu"

String.prototype.substrin…

--

--

Arek Jaworski
Arek Jaworski

Written by Arek Jaworski

Software Architect — AWS/Node.JS/JavaScript Contractor and Tutor. Combing industry experience with research!