Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex - how to get text between curly brackets

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!

like image 542
WastedSpace Avatar asked Jul 28 '10 15:07

WastedSpace


People also ask

How do you match curly brackets in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.

What is the purpose of the curly brackets {} in regular expression?

The curly brackets are used to match exactly n instances of the proceeding character or pattern. For example, "/x{2}/" matches "xx".

What are brackets in regex?

A bracket expression is either a matching list expression or a non-matching list expression. It consists of one or more expressions: ordinary characters, collating elements, collating symbols, equivalence classes, character classes, or range expressions.


1 Answers

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"]
like image 122
Christian C. Salvadó Avatar answered Oct 19 '22 23:10

Christian C. Salvadó