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

The problem is to get the string between the curly braces. Here we are going to see different Regular Expressions to get the string. 

Approach 1:

  • Selecting the string between the outer curly braces.
  • The RegExp selects the all curly braces, removes them, and then gets the content.

Example: This example illustrates the above approach. 

html




<h1 id="h1" style="color:green;">
    w3wiki
</h1>
  
<p id="GFG_UP"></p>
  
<button onclick="gfg_Run()">
    Click here
</button>
  
<p id="GFG_DOWN"></p>
  
<script>
    var el_up = document.getElementById("GFG_UP");
    var el_down = document.getElementById("GFG_DOWN");
    var st = '{This is w3wiki}';
      
    el_up.innerHTML =
        "Click on the button to get the content between"
        + " the curly brackets.<br> Str = '" + st + "'";
      
    function gfg_Run() {
        st = st.replace(/\{|\}/gi, '');
        el_down.innerHTML = st;
    }
</script>


Output:

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

Approach 2:

  • In this approach, we are selecting the string between the curly braces.
  • The RegExp selects the string from the right side. It looks for the opening curly brace from the rightmost curly brace and prints that as a string.

Example: This example illustrates the above approach. 

html




<h1 style="color:green;">
    w3wiki
</h1>
  
<p id="GFG_UP"></p>
  
<button onclick="gfg_Run()">
    Click here
</button>
  
<p id="GFG_DOWN"></p>
  
<script>
    var el_up = document.getElementById("GFG_UP");
    var el_down = document.getElementById("GFG_DOWN");
    var st = '{This is {w3wiki}}';
      
    el_up.innerHTML = "Click on the button to get the "
            + "content between the curly brackets.<br>"
            + "Str = '" + st + "'";
      
    function gfg_Run() {
        st = st.replace(/.*\{|\}/gi, '');
        el_down.innerHTML = st;
    }
</script>


Output:

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



Contact Us