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;"> zambiatek </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 zambiatek}'; 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;"> zambiatek </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 {zambiatek}}'; 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 ?
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



