Thu Oct 07 2021·2 min read
Photo by Bryan Garcia
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.
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, 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
This code snippet would also work if we had different separators.
const str = 'start!middle?end'; const middle = str.slice( str.indexOf('!') + 1, str.lastIndexOf('?'), ); console.log(middle); // 👉️ middle
-1in 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
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