In JavaScript, there are two string methods that let us extract a portion of a string with ease.
The first method substr
allows us to specify the number of characters from the start position that we wish to extract.
const sampleStr = "+11";
const count1 = sampleStr.substr(1, 1); // 1
const count2 = sampleStr.substr(1, 2); // 11
The second method substring
allows us to specify the start (inclusive) and end (not inclusive) position of the characters we wish to extract.
const sampleStr = "+1024";
const count1 = sampleStr.substring(1, 2); // 1
const count2 = sampleStr.substring(1, 3); // 10
However, if we do not specify the second parameters in both methods, it will extract the remaining of the string.
const sampleStr = "+1024";
const count1 = sampleStr.substr(1); // 1024
const count2 = sampleStr.substring(2); // 024
Top comments (2)
The substring returned by the
substring
method, as you mentioned, doesn't include the character at the end position passed to it. Your examples contradict that.Might want to change them.
Short sweet article!
My bad. Corrected.
Good spot, thanks!