Last updated: Mar 1, 2024
Reading timeยท5 min
String.split()
To get a substring between two characters:
String.slice()
method to get a substring between the 2 characters.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, '_', '#'));
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:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The 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.
start
index, we locate the first occurrence of the character and add 1
because the start
index parameter is inclusive.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.
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()
.
const str = 'bobby_hadz#com'; // ๐๏ธ hadz console.log( str.slice(str.indexOf('_') + 1, str.lastIndexOf('#')), );
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
.
const str = 'bobby_hadz#com'; // ๐๏ธ bobby_hadz console.log( str.slice(str.indexOf('@') + 1, str.lastIndexOf('#')), );
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.
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.
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.
String.split()
This is a four-step process:
String.split()
method to split the string on the first character.Array.pop()
method to get the last element from the array.String.split()
method to split the string on the second character.0
.function getSubstring(string, char1, char2) { return string.split(char1).pop().split(char2)[0]; } const str = 'bobby_hadz#com'; // ๐๏ธ hadz console.log(getSubstring(str, '_', '#'));
We used the String.split()
method to split the string on the first character.
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.
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.
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.
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, '_', '_'));
You can also pass a regular expression to the split()
method.
const str = 'bobby_hadz#com'; const result = str.split(/[_#]/); console.log(result); // ๐๏ธ [ 'bobby', 'hadz', 'com' ] console.log(result[1]); // ๐๏ธ hadz
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:
Name | Description |
---|---|
separator | The pattern describing where each split should occur. |
limit | An 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.
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.
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.
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 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.
You can learn more about the related topics by checking out the following tutorials: