A Hitchhiker's Guide to the JavaScript String Substring() Function

The String substring() function in JavaScript is a simple one, but it can be a bit difficult to grasp especially for beginners.

Here I will try to explain it in very simple terms and will keep it only to the essentials - no advanced or weird use cases!

There are two basic use cases where you will want to use the substring() function:

The Basic Use Case: Extracting a Part of a String

The most straightforward use case is extracting a part of a string.

For example, let's say our string is "pancakes" and we want to extract the "cake" part. For that, we need two inputs:

  • The starting position of "cake" in "pancake", that is, where we want to start the splitting.

  • The end position of "cake", that is, where we end the splitting.

Notice that positions in JavaScript start with 0. Counting the letters in "pancakes", we observe that the 'c' is at position 3 and the 'e' is at position 7.

Therefore, our code will be as follows:

'pancakes'.substring(3, 7); // returns 'cake'

That's it! Now you know all you need to know to use the substring() function.

However, there is a shorthand syntax that you can use in a slightly more advanced use case, which I will explain next.

The Slightly Advanced Use Case: Extracting the Last Part of a String

Let's say we have a string "oatmeal", and we want to extract the part "meal".

For that, we can use an alternative version of substring(), where we only specify the starting position of "meal" in "oatmeal".

Counting the letters, we see that the 'm' is at position 3. So our code becomes:

'oatmeal'.substring(3); // returns 'meal'

Learning More

There are many good tutorials online that explain the substring() function in more detail and with more examples.

If you are curious, I will recommend checking out this page on Mozilla MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring (also the source I used for this post)