Get String Between Two Characters in JavaScript

Get String between two characters in JavaScript

💡TL;DR
Use the substring() method to get String between two characters in JavaScript.

Here, 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.

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:

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:

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.

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() or lastIndexOf() 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:

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:

Using slice() Method

Use the slice() method to extract a substring that is between two specific characters from the given string in JavaScript.

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:

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:

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:

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.

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.

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:

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.

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:

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:

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *