Get a Substring between 2 Characters in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
5 min

banner

# Table of Contents

  1. Get a Substring between 2 Characters in JavaScript
  2. Get a Substring between 2 Characters using String.split()
  3. Get a Substring between 2 Characters using regex

# Get a Substring between 2 Characters in JavaScript

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
function getSubstring(string, char1, char2) { return string.slice( string.indexOf(char1) + 1, string.lastIndexOf(char2), ); } const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ hadz console.log(getSubstring(str, '_', '#'));

get substring between 2 characters

The code for this article is available on GitHub

The String.slice() method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

To get the start index, we locate the first occurrence of the character and add 1 because the start index parameter is inclusive.
index.js
const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ hadz#com console.log(str.slice(str.indexOf('_') + 1));

We used the String.lastIndexOf() method to get the index of the last occurrence of a character in the string.

index.js
const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ 10 console.log(str.lastIndexOf('#'));

The last index of the character is used as the stop index in the call to slice().

index.js
const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ hadz console.log( str.slice(str.indexOf('_') + 1, str.lastIndexOf('#')), );

# indexOf() and lastIndexOf() return -1 if the character doesn't exist

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.

index.js
const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ bobby_hadz console.log( str.slice(str.indexOf('@') + 1, str.lastIndexOf('#')), );

indexof and lastindexof return minus one if character does not exist

The code for this article is available on GitHub

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

If the second character doesn't exist in the string, we would extract the characters up to, but not including the last character.

index.js
const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ hadz#co console.log( str.slice(str.indexOf('_') + 1, str.lastIndexOf('@')), );

If this doesn't suit your use case, you can return an empty string if the characters aren't found.

index.js
function getSubstring(string, char1, char2) { const char1Index = string.indexOf(char1); const char2Index = string.lastIndexOf(char2); if (char1Index === -1 || char2Index === -1) { return ''; } return string.slice(char1Index + 1, char2Index); } const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ hadz console.log(getSubstring(str, '_', '#')); // ๐Ÿ‘‡๏ธ "" console.log(getSubstring(str, '@', '#')); // ๐Ÿ‘‡๏ธ "" console.log(getSubstring(str, '#', '$'));

The function checks if calling the indexOf or lastIndexOf method with the given characters returns -1.

If either of the characters is not found in the string, an empty string is returned.

Otherwise, the function returns the substring between the two characters.

Alternatively, you can use the String.split() method.

# Get a Substring between 2 Characters using String.split()

This is a four-step process:

  1. Use the String.split() method to split the string on the first character.
  2. Use the Array.pop() method to get the last element from the array.
  3. Use the String.split() method to split the string on the second character.
  4. Access the array at index 0.
index.js
function getSubstring(string, char1, char2) { return string.split(char1).pop().split(char2)[0]; } const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ hadz console.log(getSubstring(str, '_', '#'));

get substring between 2 characters using split

The code for this article is available on GitHub

We used the String.split() method to split the string on the first character.

index.js
const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz#com' ] console.log(str.split('_')); // ๐Ÿ‘‡๏ธ hadz#com console.log(str.split('_').pop());

The String.split() method returns an array containing the results.

The next step is to use the Array.pop() method to remove and return the last element from the array.

Once we have the substring after the first character, we split it on the second character.

index.js
const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ [ 'hadz', 'com' ] console.log(str.split('_').pop().split('#')); // ๐Ÿ‘‡๏ธ hadz console.log(str.split('_').pop().split('#')[0]);

The last step is to access the list at index 0 to get the result.

If the first character is not found in the string, the slice starts at the beginning and goes up to the second character.

index.js
function getSubstring(string, char1, char2) { return string.split(char1).pop().split(char2)[0]; } const str = 'bobby_hadz#com'; // ๐Ÿ‘‡๏ธ bobby_hadz console.log(getSubstring(str, '@', '#')); // ๐Ÿ‘‡๏ธ hadz#com console.log(getSubstring(str, '_', '$'));

If the second character is not found in the string, the slice goes to the end of the string.

Note that the split() approach wouldn't work if you have to split the string on the same character twice.

In this case, you should use the String.slice() approach from the previous subheading.

index.js
function getSubstring(string, char1, char2) { return string.slice( string.indexOf(char1) + 1, string.lastIndexOf(char2), ); } const str = 'bobby_hadz_com'; // ๐Ÿ‘‡๏ธ hadz console.log(getSubstring(str, '_', '_'));

# Get a Substring between 2 Characters using regex

You can also pass a regular expression to the split() method.

index.js
const str = 'bobby_hadz#com'; const result = str.split(/[_#]/); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ] console.log(result[1]); // ๐Ÿ‘‰๏ธ hadz
The code for this article is available on GitHub

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

The argument we passed to the split() method is a regular expression.

The forward slashes / / mark the beginning and end of the regex.

index.js
const str = 'bobby_hadz#com'; const result = str.split(/[_#]/); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ] console.log(result[1]); // ๐Ÿ‘‰๏ธ hadz

The part between the square [] brackets is called a character class.

The example splits the string on each occurrence of an underscore _ and a hash #, however, you can adjust the characters depending on your use case.

index.js
const str = 'bobby@hadz$com'; const result = str.split(/[@$]/); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ] console.log(result[1]); // ๐Ÿ‘‰๏ธ hadz

The code sample above splits the string on each occurrence of an @ sign and a dollar sign.

Note that the split() method splits on all occurrences of the specified characters.

index.js
const str = 'bobby_hadz#com_abc#def'; const result = str.split(/[_#]/); // [ 'bobby', 'hadz', 'com', 'abc', 'def' ] console.log(result); // hadz console.log(result[1]);
The code for this article is available on GitHub

The string contains multiple occurrences of an underscore _ and a hash # symbol, so the results array contains 5 elements.

I've also written an article on how to add a space between the characters of a string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev