.substring() explained

Definition

.substring(startIndex, endIndex) is a String method that extracts characters from a string between a defined starting index and an ending index. .substring then returns a new string made of those characters.

.substring extracts characters starting exactly at index startIndex and ending at, BUT NOT INCLUDING, the element at index endIndex.

For example, let’s say we have the following string:

const name = "Patrick";

If I wanted to extract the first 3 characters of my name and save it to a new string, I could use .substring on my name:

const name = "Patrick";
const newName = name.substring(0, 4);   // "Pat"

We used .substring(startIndex, endIndex) to extract the characters of my name starting from the character at index 0 (“P”) and ending at, BUT NOT INCLUDING the character at index 4 (“t”). This detail is one of the most important things to remember about substring. The character at endIndex is not included in the final string. The character immediately before it is included.

Note: If we accidently define a startIndex that is greater than the endIndex, then .substring will swap the two arguments. This means that: str.substring(4, 1) == str.substring(1, 4).

A negative startIndex or endIndex is automatically treated as 0:

const str = "Hello, world";
console.log(str.substring(-2, 2));  // "He"

If you only define a startIndex, but not an endIndex, .substring will extract all characters from the startIndex all the way until the end of the string:

const reallyLongString = "abcdefghijklmnopqrstuvwxyz";
console.log(reallyLongString.substring(0));  // "abcdefghijklmnopqrstuvwxyz"

If this article was helpful, tweet it!