Table of Contents
💡TL;DR
Use thesubstring()
method to get String between two characters in JavaScript.
12345678910 function getSubstring(str, start, end) {char1 = str.indexOf(start) + 1;char2 = str.lastIndexOf(end);return str.substring(char1, char2);}let originalString = "Hello,World!";let substring = getSubstring(originalString, ',', '!');console.log(substring);
123 WorldHere, we got String between
,
and!
in above example.
Using substring()
Method
Use the substring()
method to extract a substring that is between two specific characters from the given string in JavaScript.
1 2 3 4 |
let str = "This is a sample string"; console.log(str.substring(1, 3)); |
1 2 3 |
hi |
The substring()
method allows us to specify a start
and end
index for the substring we want to extract. Note that in JavaScript, string
indices start from 0
, so the 2nd character is at index 1
, and the 4th character is at index 3
.
The above example used substring()
to display characters from the specified string. Here, 1
is passed as the first argument to specify the starting position of the substring, and the second argument, 3
, represents the substring’s ending position. So, the substring hi
was returned between index 1
and 3
. Let’s see another example below:
1 2 3 4 5 6 7 |
let str = "This is a sample string"; console.log(str.substring(2)); console.log(str.substring(4, 1)); console.log(str.substring(0, 1)); console.log(str.substring(-3)); |
1 2 3 4 5 6 |
is is a sample string his T This is a sample string |
Here, we can observe that in the first console
statement, we passed only the starting position of the string to get all characters of the string starting from index 2
up to the end.
In the second console
statement, the start-index was greater than the end-index (4,1)
. So here, the substring()
method itself swapped the parameters as (1,4)
and gave results accordingly. And str.substring(0, 1)
was only used to get the string’s first character.
We can observe that the last console
statement index at the start was -3
(less than 0
). So, in that case, the substring started from index 0
to the end. Consider another example below:
1 2 3 4 5 6 7 8 9 |
let str = "This is a sample string"; let startChar = "a"; let endChar = "g"; let startIndex = str.indexOf(startChar); let endIndex = str.indexOf(endChar); let substring = str.substring(startIndex, endIndex); console.log(substring); |
1 2 3 |
a sample strin |
In this example, we first declared a string str
with the value This is a sample string
. And then, two variables, startChar
and endChar
, were declared, representing the two characters we wanted to use as the boundaries for our substring. And indexOf()
method was used to find the index of the first occurrence of each of these characters in the string.
Next, we used the substring()
method to extract the substring between these two indexes. In this case, a sample strin
substring was returned.
Note: The above solution assumes that the first character a
is guaranteed to be present, and the second character g
is also guaranteed to be present after the first character.
The substring that was returned depends on the position of the characters in the string, so if the characters we are searching for are not in the string or are in the wrong order, it will return an empty string or an error. Also, if the startChar
is the same as the endChar
and the string contains multiple instances of startChar
, it will return the substring between the first and second occurrence of startChar
.
For better understanding, create a function getSubstring()
to get a substring between two characters from the given string. This function getSubstring()
takes in three arguments:
str
is the original string from which we want to extract a substring.start
is the starting character of the substring.end
is the ending character of the substring.
1 2 3 4 5 6 7 8 9 10 |
function getSubstring(str, start, end) { char1 = str.indexOf(start) + 1; char2 = str.lastIndexOf(end); return str.substring(char1, char2); } let originalString = "Hello,World!"; let substring = getSubstring(originalString, ',', '!'); console.log(substring); |
1 2 3 |
World |
Using the indexOf()
method, we can determine the position of a value in a string based on the first occurrence, as learned above. On the other hand, the lastIndexOf()
method returns the position of a value in a string based on the last occurrence.
In the getSubstring()
function definition, char1
contained the index of the first character. And, char2
contained the index of the second character.
Note: 1
is added to the result of the indexOf()
method because we do not want to include the first character ,
in the substring we want to get. However, there is no need to exclude 1
from the lastIndexOf()
result because the character at the given end index is already omitted by substring()
.
Some important points:
-
In JavaScript, if you’re using the
indexOf()
orlastIndexOf()
method to find a substring within a string, and the given values do not exist in the string, both methods will return-1
, indicating that the substring was not found. -
If the first character of the substring does not exist in the string,
substring()
will return all the characters from the start to the last occurrence of the second character. Let’s see the below example to check this:
1 2 3 4 5 |
const string1 = 'hello:to my;World;of JavaScript!'; const result = getSubstring(string1, '-', ';'); console.log(result); |
1 2 3 |
hello:to my;World |
Here, -
was not present in string1
. That’s why it returned substring from the start to the last occurrence of the ;
. Similarly, if the second character is absent, the entire string from the start to the first instance of the first character will be included in the substring. Consider the below example to check this:
1 2 3 4 5 |
const string1 = 'hello:to my;World;of JavaScript!'; const result = getSubstring(string1, ':', '-'); console.log(result); |
1 2 3 |
hello: |
Using slice()
Method
Use the slice()
method to extract a substring that is between two specific characters from the given string in JavaScript.
1 2 3 4 5 |
let str = "Hello to my javaScript world!"; let substring = str.slice(1, 4); console.log(substring); |
1 2 3 |
ell |
The slice()
method in JavaScript can extract a substring from a string. This method takes two arguments: The substring’s starting index and ending index.
The above code snippet returned the substring ell
between the 2nd and 4th characters of the given string. We can also use the slice()
method with only one argument; it will slice the string from the given starting index until the end of the string. Check the below example:
1 2 3 4 5 |
let str = "Hello to my javaScript world!"; let substring = str.slice(9); console.log(substring); |
1 2 3 |
my javaScript world! |
The above example returned substring my javaScript world!
using the slice()
method from index 9
to the end of the string.
Suppose str.indexOf()
returned -1
due to the absence of the required character in the string. In that case, we will increment the value by 1
, which results in 0
and allows us to extract characters from the beginning of the string. Check the below example to see how to do this:
1 2 3 4 5 6 7 |
const originalStr = "Hello to my javaScript, world!"; const str= originalStr.slice( originalStr.indexOf('-') + 1, originalStr.lastIndexOf(',') ); console.log(str); |
1 2 3 |
Hello to my javaScript |
In this code, -
was not present in originalStr
. So, originalStr.indexOf('-')
returned -1
; we then added 1
, and the start index became 0
. That’s why we got the string Hello to my javaScript
from the start until we got the second character’s (,
) last occurrence`.
Consider a string, Hello to my javaScript, world!
and extract a substring between m
and !
using the slice()
method:
1 2 3 4 5 |
let str = "Hello to my javaScript, world!"; let substring = str.slice(str.indexOf("m")+1,str.indexOf("!")); console.log(substring); |
1 2 3 |
y javaScript, world |
The above code found the index of the first character m
and then added 1
to it as we wanted to exclude it from the substring. In the same way, it found the index of the second character !
and then extracted the substring y javaScript, world
between these two indexes.
Further reading:
Using split()
Method
We can also use the split()
method to extract a substring between two specific characters in a string; you will need first to split the string into an array of substrings using the first character as the separator to retrieve the desired substring from the resulting array.
1 2 3 4 5 6 |
let str = "Hi,Javascript is my favourite"; let substrings = str.split(","); let substring = substrings[1].substring(0,4); console.log(substring); |
1 2 3 |
Java |
In JavaScript, the split()
method is used to split a string into an array of substrings. It can take one or two arguments: A separator (string or regular expression) and a limit.
In this code, we used the split()
method to split the string Hi, Javascript is my favourite
into the array of substrings ["Hi", "Javascript is my favourite"]
, then we get the 2nd element from the array as substrings[1]
which is Javascript is my favourite
. After that, we extracted the first four characters, our desired substring Java
.
Now, let’s extract the last element of the string using the Array.pop()
method:
1 2 3 4 5 |
let str = "Hi,Javascript is my favourite"; let substrings = str.split(',').pop() console.log(substrings); |
1 2 3 |
Javascript is my favourite |
Here, the split()
method is used to split str
into the array having two substrings, and then the Array.pop()
method is used to remove and return the last element of the array, which is Javascript is my favourite
.
Using substr()
Method
Use the substr()
method in JavaScript to extract a substring from a given string.
1 2 3 4 5 |
let str = "Hello,to my world of JavaScript!"; let sub = str.substr(12, 5); console.log(sub); |
1 2 3 |
world |
The substr()
method takes two parameters: the starting index of the substring and the length representing the number of characters we want to extract.
In the above example, the substr()
method was used to extract the substring world
from the string Hello, to my world of JavaScript!
. Here, we wanted to get a substring from index 12
having 5
characters.
Consider a scenario where we want to get only the first character of the string:
1 2 3 4 5 |
let myStr = "Hello,to my world of JavaScript!"; let my_subStr = myStr.substr(0, 1); console.log(my_subStr); |
1 2 3 |
H |
We can observe first character H
from myStr
was returned because we have passed 0
as the starting index and 1
as the length of the substring. And if you want to get only the last character of the string, then the following solution is for you:
1 2 3 4 5 |
let myStr = "Hello,to my world of JavaScript!"; let my_subStr = myStr.substr(-1, 1); console.log(my_subStr); |
1 2 3 |
! |
In the above code snippet, -1
was used as the starting index because we wanted to extract the substring from the end with a 1
character. Now, let’s extract the last 11
characters of myStr
.
1 2 3 4 5 |
let myStr = "Hello,to my world of JavaScript!"; let my_subStr = myStr.substr(-11, 11); console.log(my_subStr); |
1 2 3 |
JavaScript! |