Get a Substring between 2 Characters in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20212 min read

banner

Photo by Bryan Garcia

Get a Substring between 2 Characters #

To get a substring between two characters, call the slice() method, passing it the index after the first occurrence of the character and the index of the last occurrence of the character as parameters.

index.js
const str = 'start_middle_end'; const middle = str.slice( str.indexOf('_') + 1, str.lastIndexOf('_'), ); console.log(middle); // ๐Ÿ‘‰๏ธ middle

The parameters 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
For our start index we have to locate the first occurrence of the character and add 1, because the start index parameter is inclusive, as opposed to the end index.

To get the index of the last occurrence of the character we use the String.lastIndexOf method.

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.

This 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 in case the character is not present in the string. This behavior can be quite confusing.

For example, if the call to str.indexOf does not find the character in the string, it would return -1.

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

There are some edge cases that you might have to cover, depending on if you're sure that the string contains the characters you pass to the indexOf and lastIndexOf methods.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee