2

I am trying to get value between multiple curly braces that startwith {{

eg :

var txt ="I expect five hundred dollars {{$500}}. and new brackets {{$600}}";

Expected Result : array of result like result[0] = "{{$500}}", result[1] = "{{$600}}"

I tried below thing, but it does not return expected result

var regExp = /\{([^)]+)\}/g;
var result = txt.match(regExp);

JsFiddle Link

Richa
  • 3,261
  • 2
  • 27
  • 51

4 Answers4

2

You can use a simple regex like /{{\w+:(\$\d+)}}/g, then get each match using RegExp#exec function and extract the value from the captured group.

var txt = "I expect five hundred dollars {{rc:$500}}. and new brackets {{ac:$600}}";

var reg = /{{\w+:(\$\d+)}}/g,
  m,
  res = [],
  res2 = [];

while (m = reg.exec(txt)) {
  res.push(m[0]);
  res2.push(m[1]);
}

console.log(res,res2)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Use match and map, regex as /(?:({{))[^}]+(?=}})/g

var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";
var matches = txt.match( /(?:({{))[^}]+(?=}})/g );
if ( matches )
{
   matches = matches.map( s => s.substring(2) );
}
console.log( matches  );

Demo

var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";
var matches = txt.match(/(?:({{))[^}]+(?=}})/g);
if (matches) {
  matches = matches.map(s => s.substring(2));
}
console.log(matches);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Change you code like this

var txt ="I expect five hundred dollars {{$500}}. and new brackets {{$600}}";
function getText(str) {
  var res = [], p = /{{([^}]+)}}/g, row;

  while(row = p.exec(str)) {
    res.push(row[1]);
  }
  return res;
}
console.log(getText(txt)); 
freelancer
  • 1,174
  • 5
  • 12
0

String#match will always return the full matched regular expression without using capture groups. You could use String#replace with a callback function to add each match to an array.

var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";

var regExp = /{{ac:([^\}]+)}}/g;

function matches(regExp, txt) {
  const result = []
  txt.replace(regExp, (_, x) => result.push(x));
  return result
}

console.log(matches(regExp, txt))
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
synthet1c
  • 6,152
  • 2
  • 24
  • 39