Ganesh Rathinavel
Ganesh Rathinavel

Reputation: 1345

Javascript get substring values within the curly braces

I was looking for regexp to get values in between the curly braces, but the examples found on internet are limited to just one substring while I need to get all the substrings values which are matching the pattern. eg:

The {Name_Student} is living in {City_name}

How can I get the values of substrings in between the curly braces({}), in an array if possible! I am trying to implement this in javascript.

Thanks in advance :)

Upvotes: 1

Views: 2280

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

The below regex would capture the values inside curly braces into the first group.

\{([^}]*)\}

DEMO

Upvotes: 1

elclanrs
elclanrs

Reputation: 94141

Match the values, then remove the curlys:

str.match(/\{.+?\}/g).map(function(x){return x.slice(1,-1)})

Or you can do this with capture groups:

var res = []
str.replace(/\{(.+?)\}/g, function(_, m){res.push(m)})

Upvotes: 4

zx81
zx81

Reputation: 41848

The regex {([^}]+)} captures all the matches to Group 1 (see the captures in the right pane of the regex demo). The code below retrieves them.

In JavaScript

var the_captures = []; 
var yourString = 'your_test_string'
var myregex = /{([^}]+)}/g;
var thematch = myregex.exec(yourString);
while (thematch != null) {
    // add it to array of captures
    the_captures.push(thematch[1]);
    document.write(thematch[1],"<br />");    
    // match the next one
    thematch = myregex.exec(yourString);
}

Explanation

  • We capture the strings to Group 1. The code retrieves them and adds them to an array.
  • { matches the opening brace
  • ([^}]+) captures all chars that are not a closing brace to Group 1
  • } matches the closing brace

Upvotes: 2

Related Questions