11

I am trying to get content between curly braces with JavaScript. I found this thread: Regex to get string between curly braces "{I want what's between the curly braces}"

But I do not know how to apply a regex like /\{([^}]+)\}/

I have tried string.replace('/\{([^}]+)\}/','');, however this does not work.

Ivar
  • 4,655
  • 12
  • 45
  • 50
alex
  • 813
  • 2
  • 8
  • 10

5 Answers5

33

Here's an example of use:

var found = [],          // an array to collect the strings that are found
    rxp = /{([^}]+)}/g,
    str = "a {string} with {curly} braces",
    curMatch;

while( curMatch = rxp.exec( str ) ) {
    found.push( curMatch[1] );
}

console.log( found );    // ["string", "curly"]
meouw
  • 40,162
  • 10
  • 48
  • 67
6

Try this

/[^{\}]+(?=})/g

for example

Welcome to RegExr v2.1 by {gskinner.com}, {ssd.sd} hosted by Media Temple!

it will return 'gskinner.com', 'ssd.sd'

default locale
  • 11,849
  • 13
  • 52
  • 59
6

Like this?

var x="omg {wtf} bbq";

alert(x.match(/{([^}]+)}/));
Khez
  • 9,646
  • 2
  • 28
  • 51
2
"{I want what's between the curly braces}".replace(/{(.*)}/, "$1");

this should work, cheers.

Note: you'll "get everything" in the braces, even if it's an empty string.

Updated: If you are going to match the first character which in the middle of a string, use "match":

"how are you {I want what's between the curly braces} words".match(/{(.*)}/)[1];

You can just do:

console.log("how are you {I want what's between the curly braces} words".match(/{(.*)}/));

then you'll see a list of the match items, exploit them to whatever you want.

Gory details: http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Linmic
  • 701
  • 4
  • 10
  • @alex what version of IE are you using? I've just tested it in IE9, like this: http://img801.imageshack.us/i/reie.png/, actually I did IE7, 8 as well, all work fine. – Linmic Apr 02 '11 at 03:54
0

This will return an array of matching text.
the map function will return the text without {}.

const text = "Regex to get string between curly braces {I want what's between the curly braces}"
const result = text.match(/{([^}]+)}/g)
  .map(res => res.replace(/{|}/g , ''))