How to use Regex to get the string between curly braces using JavaScript?


We can create a regular expression so it can find all the substrings between the curly braces. After that, we can use the exec() or match() method to extract the matching substring.

In this tutorial, we will learn to use a regular expression to get the string between curly braces using JavaScript. For example, if we have given a string like ‘This is a {string} with {curly} braces, we need to extract all substrings that reside between the curly braces.

Using the exec() method with a regular expression to get the string between curly braces

The exec() method is generally used with the regular expression to find the matched substrings. It returns all matching results in the array format, and if it doesn’t find any matching occurrence, it returns the null values.

Syntax

Users can follow the syntax below to use the exec() method with the regular expression to get all substrings between the curly braces.

var regex = /{([^}]+)}/g;
while (match = regex.exec(originalStr)) {
   results.push(match[1]);
}

In the above syntax, we have created the regex to find substring between curly braces. After that, we iterate through the match array and get all matching occurrences.

Example

The ‘originalStr’ variable contains string with curly braces in the example below. The regex.exec() method returns the 2D array of all matching substrings. Every element of the array is an array of 2 strings. The first element is a string with curly braces, and the second is a string without curly braces, which we want to extract.

In the output, users can observe that it shows the ‘Developers’ and ‘JavaScript’ substrings as they both are between the curly braces.

<html>
<body>
   <h3>Using the <i> regular expression and exec() method </i> to get string between curly braces in JavaScript</h3>
   <div id = "demo"> </div>
   <script>
      let output = document.getElementById("demo");
      function getStringBetweenBraces() {
         var originalStr = "Hello {Developers}! Let's develop {JavaScript} code!";
         var found = [];
         var regex = /{([^}]+)}/g;
         var results = [];
         let match;
         while (match = regex.exec(originalStr)) {
            results.push(match[1]);
         }
         output.innerHTML = "The original string is " + originalStr + "<br>";
         output.innerHTML += "The substrings between curly braces are " + results + "<br>";
      }
      getStringBetweenBraces();
   </script>
</body>
</html>

Using the match() method with a regular expression to get the string between curly braces

The match() method also returns all matching occurrences from the string in the array format.

Syntax

Users can follow the syntax below to use the match() method with a regular expression to get the string between curly braces

let results = originalStr.match(/{([^}]+)}/g); 

In the above syntax, originalStr is a string with curly braces, and we have passed the regular expression as a match() method parameter.

Example

In the example below, the match() method returns the array of strings with curly braces. However, it doesn’t return the string after removing the curly braces. Users can use the subStr() or substring() method to remove the curly braces from the returned results.

<html>
<body>
   <h3>Using the <i> regular expression and match() method </i> to get string between curly braces in JavaScript</h3>
   <div id = "demo"> </div>
   <script>
      let output = document.getElementById("demo");
      function getStringBetweenBraces() {
         var originalStr = "This is {sample} string! This is {original} string!";
         let results = originalStr.match(/{([^}]+)}/g); 
         output.innerHTML = "The original string is " + originalStr + "<br>";
         output.innerHTML += "The substrings between curly braces are " + results + "<br>";
      }
      getStringBetweenBraces();
   </script>
</body>
</html>

Using the for loop to get the string between curly braces

We can also extract all the substrings between the curly braces by iterating through the string using for loop. We can keep track of the curly braces' starting and end indexes of the curly braces. After that, we can use the substring() method to extract the sub-string from the original string.

Syntax

Users can follow the syntax below to use the for loop to extract the substrings between the curly braces.

for ( ) {
   if (str[i] == "{")
   start = i;
   if (str[i] == "}") {
      end = i;
      let bracesString = str.substring(start + 1, end);
   }
}   

In the above syntax, we keep track of curly braces' start and end index and use the substring() method to extract the strings.

Steps

Step 1 − Use the for loop to iterate through the string.

Step 2 − If a character in the string at index ‘I’ is equal to the ‘{‘, store the value of the index in the start variable.

Step 3 − If a character in the string at index ‘I’ is equal to the ‘}‘, store the value of the index in the end variable.

Step 3.1 − Use the substring() method to get the substring between the ‘start + 1’ index of the ‘end’ index.

Step 3.2 − Push the resultant substring into the array.

Example

In the example below, we have followed the above steps to extract the strings between the curly braces using the for a loop. However, this approach is not used to extract the strings between nested curly braces.

<html>
<body>
   <h3>Using the <i> for loop </i> to get string between curly braces in JavaScript</h3>
   <div id = "demo"> </div>
   <script>
      let output = document.getElementById("demo");
      function getStringBetweenBraces() {
         var str = "Hello {Users}! Welcome to {Website}!";
         var start = 0;
         var end = 0;
         let results = [];
         for (var i = 0; i < str.length; i++) {
            if (str[i] == "{") {
               start = i;
            }
            if (str[i] == "}") {
               end = i;
               let bracesString = str.substring(start + 1, end);
               results.push(bracesString);
            }
         }
         output.innerHTML = "The original string is " + str + "<br>";
         output.innerHTML += "The substrings between curly braces are " + results + "<br>";
      }
      getStringBetweenBraces();
   </script>
</body>
</html> 

We learned to extract the string between the curly braces using the Regular expression in this tutorial. In the first approach, we used the exec() method with regular expression; in the second approach, we used the match() method with regular expression.

In the third approach, we used the for loop instead of the regular expression.

Updated on: 06-Mar-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements