Get a Substring between 2 Characters in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get a Substring between 2 Characters #

To get a substring between two characters:

  1. Get the index after the first occurrence of the character.
  2. Get the index of the last occurrence of the character.
  3. Use the String.slice() method to get a substring between the 2 characters.
index.js
const str = 'start_middle_end'; const middle = str.slice( str.indexOf('_') + 1, str.lastIndexOf('_'), ); console.log(middle); // 👉️ middle

The arguments we passed to the String.slice method are:

  1. start index - the index of the first character to include in the new string
  2. end index - include characters up to, but not including this index
To get the start index, we locate the first occurrence of the character and add 1 because the start index parameter is inclusive.

We used the String.lastIndexOf method to get the index of the last occurrence of the character.

Even if we had other underscore characters in the string, they would be included in the returned string because we locate the first and last occurrence of the _ character.

The code snippet would also work if we had different separators.

index.js
const str = 'start!middle?end'; const middle = str.slice( str.indexOf('!') + 1, str.lastIndexOf('?'), ); console.log(middle); // 👉️ middle
Note that the indexOf and lastIndexOf methods return -1 if the character is not present in the string. This behavior can be quite confusing.

For example, if the call to str.indexOf doesn't find the character in the string, it would return -1.

We would then increment the value by 1, which equals to 0, so we would start extracting characters at the beginning of the string.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.