Open In App

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:



Example: This example illustrates the above approach. 




<h1 id="h1" style="color:green;">
    GeeksforGeeks
</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 GeeksforGeeks}';
      
    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:

Example: This example illustrates the above approach. 




<h1 style="color:green;">
    GeeksforGeeks
</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 {GeeksforGeeks}}';
      
    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 ?


Article Tags :