8

I need to get the text (if any) between curly brackets. I did find this other post but technically it wasn't answered correctly: Regular expression to extract text between either square or curly brackets

It didn't actually say how to actually extract the text. So I have got this far:

var cleanStr = "Some random {stuff} here";
var checkSep = "\{.*?\}"; 
if (cleanStr.search(checkSep)==-1) { //if match failed
  alert("nothing found between brackets");
} else {
  alert("something found between brackets");
}

How do I then extract 'stuff' from the string? And also if I take this further, how do I extract 'stuff' and 'sentence' from this string:

var cleanStr2 = "Some random {stuff} in this {sentence}";

Cheers!

Community
  • 1
  • 1
WastedSpace
  • 1,143
  • 6
  • 22
  • 34

2 Answers2

21

To extract all occurrences between curly braces, you can make something like this:

function getWordsBetweenCurlies(str) {
  var results = [], re = /{([^}]+)}/g, text;

  while(text = re.exec(str)) {
    results.push(text[1]);
  }
  return results;
}

getWordsBetweenCurlies("Some random {stuff} in this {sentence}");
// returns ["stuff", "sentence"]
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • @WastedSpace: You're welcome!. Note that I've added the variable declaration of `text` that was missing. – Christian C. Salvadó Jul 28 '10 at 16:49
  • Hi CMS, Sorry to be a pain (I thought I could figure this out for myself), but how do you then go about parsing EVERYTHING from that sentence into array values like so (in this order): Some random ,{stuff}, in this ,{sentence}. Thanks :) – WastedSpace Aug 04 '10 at 14:02
-1

Create a "capturing group" to indicate the text you want. Use the String.replace() function to replace the entire string with just the back reference to the capture group. You're left with the text you want.

Jay
  • 13,803
  • 4
  • 42
  • 69